SQL 根据匹配值将多行合并为单行

SQL merge several rows into Single row on matching value

我想要做的是合并几行数据以显示为一行。

来自这个:

Contract ID Contract group ID Amount
140 189 90.00
140 190 85.00
140 191 300.00
151 190 10.00
152 189 200.00
152 191 50.00

对此:

Contract ID Group 189 Group 190 Group 191 Total amount
140 90.00 85.00 300.00 475.00
151 00.00 10.00 00.00 10.00
152 200.00 00.00 50.00 50.00

欢迎提出任何建议。

谢谢。

您可以使用条件聚合:

select contractid,
    max(case when contractgroupid = 189 then amount else 0 end) as group_189,
    max(case when contractgroupid = 190 then amount else 0 end) as group_190,
    max(case when contractgroupid = 191 then amount else 0 end) as group_191,
    max(case when contractgroupid = 192 then amount else 0 end) as group_192,
    sum(amount) as total_amount
from mytable
group by contractid

如果同一组对于给定合同可能出现多次,您可能希望使用 sum() 而不是 max()