合并2行成为1行

时间:2013-11-12 13:21:13

标签: sql sql-server

我有这样的数据

MemberId | VesselName | Cargo | Date
B001     | Ship A     | 500   | 2013/11/12
B001     | Ship X     | 250   | 2013/11/20
B003     | Ship Y     | 300   | 2013/11/11

我想要这样的查询结果

MemberId | VesselName    | Cargo | Date
B001     | Ship A Ship X | 750   | 2013/11/12 2013/11/20
B003     | Ship Y        | 300   | 2013/11/11

1 个答案:

答案 0 :(得分:0)

困难的部分是将多个VesselNames放在一起......

如果每个成员最多有2艘船,您可以执行以下操作:

select MemberId, 
       min(VesselName) + " " + max(VesselName) as Names, 
       sum(Cargo) as TotalCargo,
       cast(min(Date) as char(20)) + ' to ' + cast(max(Date) as char(20)) as Dates
from YourTable
group by MemberId