汇总共享公共值但具有唯一行标识符的多个事务

时间:2014-08-15 23:49:31

标签: sql sql-server-2008 group-by

我目前正在使用具有大量唯一组的数据集,并且在每个组中可能有一对多的唯一行,以描述适用于该组的事务类型。交易类型有限,每笔交易都有(n):

  • 金额
  • 位置
  • 日期

数据集看起来像这样:

enter image description here

我希望它能将所有组合成一行,每种类型的事务都有三列。我试图让最终结果看起来像这样:

enter image description here

我最接近的是在寻找唯一密钥时根据索赔号尝试多个连接。不幸的是,我的结果看起来像这样:

enter image description here

有关如何让每个唯一群组在结果中一行的任何建议,其中三种类型展开,每行有三列?

1 个答案:

答案 0 :(得分:1)

您可以使用条件聚合完成所有操作:

select   grp,
         sum(case when type = 'S' then amount else null end) as type_s_amt,
         min(case when type = 'S' then location else null end) as type_s_loc,
         min(case when type = 'S' then date else null end) as type_s_dt,
         sum(case when type = 'O' then amount else null end) as type_o_amt,
         min(case when type = 'O' then location else null end) as type_o_loc,
         min(case when type = 'O' then date else null end) as type_o_dt,
         sum(case when type = 'F' then amount else null end) as type_f_amt,
         min(case when type = 'F' then location else null end) as type_f_loc,
         min(case when type = 'F' then date else null end) as type_f_dt
from     tbl
group by grp

小提琴: http://sqlfiddle.com/#!3/f7fae/5/0