mysql 将结果以列显示_mysql 行转列 (结果集以坐标显示)

这篇博客探讨了如何使用SQL进行数据分组和求和操作。首先创建了一个名为'capacity'的表,包含'type'、'numbers'和'months'字段。接着,展示了两个查询:第一个按'type'分组并计算每个月的numbers总和;第二个进一步按季度分组,将每个月的numbers求和,以获取每个季度的总和。这些查询对于理解和处理时间序列数据十分有用。
摘要由CSDN通过智能技术生成

create table capacity(

typeint,

numbersint,

monthst INT

);

select type,

sum(case monthst when 1 then numbers else 0 end ) 一月,

sum(case monthst when 2 then numbers else 0 end ) 二月,

sum(case monthst when 3 then numbers else 0 end ) 三月,

sum(case monthst when 4 then numbers else 0 end ) 四月,

sum(case monthst when 5 then numbers else 0 end ) 五月,

sum(case monthst when 6 then numbers else 0 end ) 六月,

sum(case monthst when 7 then numbers else 0 end ) 七月,

sum(case monthst when 8 then numbers else 0 end ) 八月,

sum(case monthst when 9 then numbers else 0 end ) 九月,

sum(case monthst when 10 then numbers else 0 end ) 十月,

sum(case monthst when 11 then numbers else 0 end ) 十一月,

sum(case monthst when 12 then numbers else 0 end ) 十二月

from capacity group by type;

按type分组,并对每月的对应type的numbers求和。

6a28058fcc4949981caafb6f377c3378.png

select cap.type,sum(cap.a+cap.b+cap.c) 一季度,sum(cap.d+cap.e+cap.f) 二季度,sum(cap.g+cap.h+cap.i) 三季度,sum(cap.j+cap.k+cap.l) 四季度 from

(select type,

sum(case monthst when 1 then numbers else 0end ) a,

sum(case monthst when 2 then numbers else 0end ) b,

sum(case monthst when 3 then numbers else 0end ) c,

sum(case monthst when 4 then numbers else 0end ) d,

sum(case monthst when 5 then numbers else 0end ) e,

sum(case monthst when 6 then numbers else 0end ) f,

sum(case monthst when 7 then numbers else 0end ) g,

sum(case monthst when 8 then numbers else 0end ) h,

sum(case monthst when 9 then numbers else 0end ) i,

sum(case monthst when 10 then numbers else 0end ) j,

sum(case monthst when 11 then numbers else 0end ) k,

sum(case monthst when 12 then numbers else 0end ) l

from capacity group by type) cap

group by cap.type;

再对每行多列合并求和。

9f474008f12514fe6a31a9972382fc7b.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值