[整理]一行變多行(Oracle)

來源:[url]http://www.itpub.net/thread-1156433-1-1.html[/url]
cjh2000提問:
現有數據表中的數據形式爲:
名稱 數量 單價
a 4 10
b 2 8
現在能否通過一個SQL語句將其變成:
名稱 數量 單價
a 1 10
a 1 10
a 1 10
a 1 10
b 1 8
b 1 8

grova解答:
SQL> create table tt(name varchar2(10),num number,price number);


表已創建。

SQL> insert into tt values('a',4,10);


已創建 1 行。

SQL> insert into tt values('b',2,8);


已創建 1 行。

SQL> commit;


SQL> select name,1 num,price
2 from tt,(select rownum rn from dual connect by level<=5)
3 where rn between 1 and num
4 order by name;


NAME NUM PRICE
---------- ---------- ----------
a 1 10
a 1 10
a 1 10
a 1 10
b 1 8
b 1 8

已選擇6行。

atgc解答:
SQL> select * from test;


NA F1 F2
-- ---------- ----------
a 4 10
b 2 8

SQL> select * from test2;


RN
----------
1
2
3
4

SQL> select a.name,1 f1,a.f2 from test a,test2 b
2 where b.rn<=a.f1;


NA F1 F2
-- ---------- ----------
a 1 10
a 1 10
a 1 10
a 1 10
b 1 8
b 1 8

6 rows selected.

轉帖:利用整數表解決複雜SQL查詢——案例二
http://space.itpub.net/15203236/viewspace-590898
問題描述:

Count匯聚一組行,並告訴每一組有多少行數據。但是,如果想得到相反的過程,將匯聚結果回推到多行數據時,該怎麼辦呢?

一旦得到了匯聚數據,將其分離開來就會十分棘手。例如,有一個包含賓館房間預訂的表bookings,每一行都有一個指明預訂第一夜的日期、總費用以及預訂天數。

Startwhn
Visitprice
Nights
2005-01-01
100
2
2005-02-01
200
5

在已知這些信息的情況下,弄清楚某個特定夜晚被預訂了多少個房間是件困難的事情。我們希望處理這些信息,以便得到這樣的結果:客人停留的每一夜都包含一行。Desired表的格式如下:

Startwhn
Whn
prices
2005-01-01
2005-01-01
50
2005-01-01
2005-01-02
50
2005-02-01
2005-02-01
40
2005-02-01
2005-02-02
40
2005-02-01
2005-02-03
40
2005-02-01
2005-02-04
40
2005-02-01
2005-02-05
40

很容易從desired得到booking,但這是我們需要做的事情的反過程:

Select startwhn,sum(price),count(price)
From desired group by startwin;

解決方案:

從booking得到desired需要更深入的思考,可是通過使用一個整數表來解決這個問題:
Integers表包含了單個列,保存了從1到某個更大整數之間的數字,在本問題的情況下,integers表至少要達到任何客人預訂的最大天數。這樣:
Create table integers(n int primary key);
Insert into integers values(1);
Insert into integers values(2);
Insert into integers values(3);
Insert into integers values(4);
Insert into integers values(5);
……..
或者也可以這樣來實現插入數據:
Insert into integers select rownum rn from dual connect by level<=5;

在各種查詢中integers都是一個有用的表,生成desired表的關鍵是將integers交叉連接到bookings上,使用條件n不大於nights:

SQL> select startwhn,startwhn+n-1 as whn, visitprice/nights as price
2 from bookings,integers
3 where n between 1 and nights;

STARTWHN WHN PRICE
-------------- -------------- ----------
01-1月-05 01-1月-05 50
01-1月-05 02-1月-05 50
01-2月-05 01-2月-05 40
01-2月-05 02-2月-05 40
01-2月-05 03-2月-05 40
01-2月-05 04-2月-05 40
01-2月-05 05-2月-05 40

已選擇7行。
發佈了69 篇原創文章 · 獲贊 0 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章