2012-08-13 128 views
3

假設我有id, name, phone_type, phone_no如何將兩條記錄合併成一條線?

和一張桌子我有2個記錄

{1, Tom, home, 123} 
{2, Tom, mobile, 234} 

如果我只是用SQL:

SELECT * FROM table WHERE name = tom; 

它會顯示兩條記錄。

不過,我想在這樣一個線顯示:

Tom, mobile,234,home,123 

類似的東西...

我怎麼能修改在DB2中的SQL?

請幫忙。

+0

你在輸出中尋找什麼列? – 2012-08-13 14:52:38

+0

**什麼**數據庫系統,以及哪個版本? * SQL *只是*結構化查詢語言* - 許多數據庫系統使用的語言,但不是數據庫產品......這樣的功能通常是特定於供應商的 - 因此我們確實需要知道**數據庫系統**你正在使用.... – 2012-08-13 14:54:30

+0

看看http://stackoverflow.com/questions/194852/concatenate-many-rows-into-a-single-text-string中的答案 – 2012-08-13 14:55:20

回答

0

這裏有一種方法:

select name, 
     'mobile', 
     max(case when ttype = 'mobile' then phone end) as mobilephone, 
     'home', 
     max(case when ttype = 'home' then phone end) as homephone 
from t 
group by name 
0

這可能會給一個想法

declare @rVal nvarchar(128) 
set @rVal = 'Tom' 
select @rVal = @rval + coalesce(',' + phoneType + ',' + convert(nvarchar,phoneNumber),'') from testTable where name = 'Tom' 
select @rVal 
+0

這是我的DB2版本(在iSeries上)無效的語法,並且不會返回反正連接的行(僅列,這很愚蠢)。而'COALESCE()'是沒用的,因爲它總是有數據(因爲'','')。如果你期望這是在一個循環中運行......你需要在處理SQL時停止像命令程序員那樣的思考(你正在與系統打交道)。 – 2012-08-14 16:17:07

1

下面是使用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子句中。

+0

並非所有版本的DB2都支持'lead()',儘管OP沒有列出他正在使用的版本。這也將結果限制爲4個電話號碼 - 如果所有的OP需求都是2,我可能只是嘗試自聯接,而不是嘗試使用OLAP功能;如果他需要超過4個,你將需要其他東西...... – 2012-08-14 16:22:58

+0

正如我所提到的,這將很容易擴展到4以上。只需添加更多的lead()線對,直到您可以處理最大值可能與您的數據的情況。不,這種解決方案並不美觀,但遺憾的是,在DB2中沒有一種好的方法來實現這一點。 – dan1111 2012-08-16 08:13:30