这个主题还是比较常见的,行转列主要适用于对数据作聚合统计,如统计某类目的商品在某个时间区间的销售情况。列转行问题同样也很常见。
group by + sum + case when实现行转列:
SELECT A.ORG_ID, A.tv_type_count, A.tv_file_count, A.tv_date, CASE train_id WHEN '1' THEN 'ZHI' WHEN '2' THEN 'XING' WHEN '3' THEN 'SHI' WHEN '4' THEN 'KETANG' ELSE NULL END "train_type" FROM T_SYS_LOG A WHERE org_id = 'xxx'
查询出来的结果是这样:
这时我就在想要满足前端的展示,一定要将train_type进行一个分解,实现ZHIFA这种类型的数据按照日期进行一个单条数据展示,我就将这条sql抽取了出来:
SELECT A.ORG_ID, A.tv_date, A.tv_type_count, A.tv_file_count FROM T_SYS_LOG A WHERE org_id = 'xxx'
然后就是sql的行转列了:
SELECT A.ORG_ID, A.tv_date, SUM ( CASE A.train_id WHEN '1' THEN A.tv_type_count ELSE 0 END) AS fa_type_count, SUM ( CASE A.train_id WHEN '1' THEN A.tv_file_count ELSE 0 END) AS zhi_file_count, SUM ( CASE A.train_id WHEN '2' THEN A.tv_type_count ELSE 0 END) AS zheng_type_count, SUM ( CASE A.train_id WHEN '2' THEN A.tv_file_count ELSE 0 END) AS xing_file_count, SUM ( CASE A.train_id WHEN '3' THEN A.tv_type_count ELSE 0 END) AS shi_type_count, SUM ( CASE A.train_id WHEN '3' THEN A.tv_file_count ELSE 0 END) AS xis_file_count, SUM ( CASE A.train_id WHEN '4' THEN A.tv_type_count ELSE 0 END) AS ke_type_count, SUM ( CASE A.train_id WHEN '4' THEN A.tv_file_count ELSE 0 END) AS tang_file_count FROM T_SYS_LOG A WHERE A.org_id = 'xxx' GROUP BY A.tv_date,A.ORG_ID ORDER BY A.tv_date Desc
在这里根据不同的train_id类型来进行取值,因为每个类型都具有两个关键字段信息,所以在进行一个AS重命名,为了防止在前端出现undefine,如果查询的对应值为空的话,我们ELSE为0,同时根据时间进行分组。