首页 > 解决方案 > SQL:需要查询具有多种交易类型的单列并以表格格式输出

问题描述

我需要查询一个包含几种不同类型事务记录的表: 桌子

并以表格格式生成输出(当然不使用 Excel 数据透视表): 在此处输入图像描述

有没有比加入多个子查询更好的方法来做到这一点?如果没有更好的方法,我应该如何处理 JOIN 的顺序?

标签: sqloracle

解决方案


只需使用条件聚合:

select yyyymm,
       sum(case when type = 'CNFF Iny' then amount end) as cnff_iny,
       sum(case when type = 'CNFF Ret' then amount end) as cnff_ret,
       . . .   -- and so on for all the values
from t
group by yyyymm
order by yyyymm;

推荐阅读