如何将两个记录合并为一行?

时间:2012-08-13 14:50:54

标签: sql db2

假设我有一个包含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?

请帮忙。

3 个答案:

答案 0 :(得分: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子句。

答案 1 :(得分: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

答案 2 :(得分:0)

这可能会给出一个想法

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