select ts , case when code='abc' then value end as abc, case when code='cde' then value end as cde case when code='fgh' then value end as fgh from ( select ts,code,sum(value) as value from 表 group by ts,code)tt group by ts , case when code='abc' then value end as abc, case when code='cde' then value end as cde case when code='fgh' then value end as fgh
发布评论
评论(4)
可以考虑采用tablefunc扩展,做个行列转换,pg官网文档写很细了
不过如果就这点量,上面的答案够简单了
这个很简单group by code再case when一下就可以了.即先分组,行转列,值得注意的是这个需要动态sql生成,即你的sql需要拼接,因为你的列abc cde fgh这个并不是一个固定的列数。如果只是这三列可以固定写,如果不是则需要动态生成sql 中的case when 。
这是分组后的行转列吗 ?
select
ts ,
case when code='abc' then value end as abc,
case when code='cde' then value end as cde
case when code='fgh' then value end as fgh
from (
select ts,code,sum(value) as value from 表
group by ts,code)tt
group by
ts ,
case when code='abc' then value end as abc,
case when code='cde' then value end as cde
case when code='fgh' then value end as fgh