下面是使用OLAP功能更通用的例子。這將獲得每個名稱的前四對電話類型和電話號碼。如果有人少於四人,剩下的人將被填入NULL。很明顯,你如何將這個擴展到四個以上。
select * from (
select id,
min(id) over (partition by name) as first_id,
name,
phone_type as phone_type1,
phone_no as phone_no1,
lead(phone_type,1) over (partition by name order by id) as phone_type2,
lead(phone_no,1) over (partition by name order by id) as phone_type2,
lead(phone_type,2) over (partition by name order by id) as phone_type3,
lead(phone_no,2) over (partition by name order by id) as phone_type3,
lead(phone_type,3) over (partition by name order by id) as phone_type4,
lead(phone_no,3) over (partition by name order by id) as phone_type4
from table
) where id = first_id
外部選擇保證你每人只能得到一行。您需要這樣做是因爲OLAP函數的結果(本例中爲min(id)
)不能直接放入where子句中。
你在輸出中尋找什麼列? – 2012-08-13 14:52:38
**什麼**數據庫系統,以及哪個版本? * SQL *只是*結構化查詢語言* - 許多數據庫系統使用的語言,但不是數據庫產品......這樣的功能通常是特定於供應商的 - 因此我們確實需要知道**數據庫系統**你正在使用.... – 2012-08-13 14:54:30
看看http://stackoverflow.com/questions/194852/concatenate-many-rows-into-a-single-text-string中的答案 – 2012-08-13 14:55:20