SQL Concat行(如果ID重复)

时间:2018-06-27 19:07:27

标签: sql sql-server

如果ID重复,是否可以合并行?

例如

ROOM_ID   LINE   ROOM_ADDRESS
001       1      100 Washington St
001       2      Unit 2
002       1      200 California St
003       1      150 Alabama St
003       2      Unit 1

如果我要GROUP BY ROOM_ID,我会在第2行中丢失信息。那么有没有办法得到以下结果:

ROOM_ID   ROOM_ADDRESS
001       100 Washington St Unit 2
002       200 California St
003       150 Alabama St Unit 1

谢谢

1 个答案:

答案 0 :(得分:1)

如果只有几行,则条件聚合可能是最简单的方法:

select room_id,
       (max(case when line = 1 then room_address else '' end) +
        max(case when line = 2 then ' ' + room_address else '' end) +
        max(case when line = 3 then ' ' + room_address else '' end)
       ) as room_address
from t
group by room_id;

请注意,这不能很好地泛化,但是对于两个或三个地址,效果很好。

您可以使用left join做类似的事情:

select t1.room_id,
       (t1.address + coalesce(' ' + t2.address, '') + coalesce(' ' + t3.address, '')) as room_address
from t t1 left join
     t t2
     on t1.room_id = t2.room_id and t2.line = 2 left join
     t t3
     on t1.room_id = t3.room_id and t3.line = 3
where line = 1;