假设我有一个包含列的表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?
请帮忙。
这是一个使用 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 子句中。
这是一种方法:
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
这可能会给出一个想法
declare @rVal nvarchar(128)
set @rVal = 'Tom'
select @rVal = @rval + coalesce(',' + phoneType + ',' + convert(nvarchar,phoneNumber),'') from testTable where name = 'Tom'
select @rVal