我目前正在使用具有大量唯一组的数据集,并且在每个组中可能有一对多的唯一行,以描述适用于该组的事务类型。交易类型有限,每笔交易都有(n):
数据集看起来像这样:
我希望它能将所有组合成一行,每种类型的事务都有三列。我试图让最终结果看起来像这样:
我最接近的是在寻找唯一密钥时根据索赔号尝试多个连接。不幸的是,我的结果看起来像这样:
有关如何让每个唯一群组在结果中仅一行的任何建议,其中三种类型展开,每行有三列?
答案 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