sql - 像百事可乐这样的 SQL SERVER PIVOT 低于一年,然后是几个月等等。(请参阅附图以获得清晰的想法)
问题描述
我是 PIVOT 的新手……所以我不知道是否可以使用 Pivot。
这是我使用的表格和示例数据
create table sales_history (brandcode varchar(10) ,
syear smallint,
smonth smallint,
salesvalues float )
insert into sales_history values ('PPS', 2018,1, 256400.00), ('PPS', 2018,2, 278650.00), ('PPS', 2018,3, 236500.00)
insert into sales_history values ('CCL', 2018,1, 356200.00), ('CCL', 2018,2, 365100.00), ('CCL', 2018,3, 174300.00)
insert into sales_history values ('MND', 2018,1, 275200.00), ('MND', 2018,2, 415180.00), ('MND', 2018,3, 274500.00)
insert into sales_history values ('PPS', 2019,1, 356400.00), ('PPS', 2019,2, 378650.00), ('PPS', 2019,3, 336500.00)
insert into sales_history values ('CCL', 2019,1, 456200.00), ('CCL', 2019,2, 465100.00), ('CCL', 2019,3, 274300.00)
insert into sales_history values ('MND', 2019,1, 375200.00), ('MND', 2019,2, 515180.00), ('MND', 2019,3, 374500.00)
-- PRIVOT 查询
select *
from (
select *
from sales_history
) as t1
pivot
(sum (salesvalues) for syear IN ([2018],[2019]))
as pivot_brand_sales
使用上面的查询,我得到了附件中的输出
[请查看我正在尝试的所需输出的附件以及我使用上述查询获得的输出]
解决方案
我会为此使用条件聚合:
select
brandcode,
sum(case when syear = 2018 and smonth = 1 then salesvalue else 0 end) [2018-01],
sum(case when syear = 2018 and smonth = 2 then salesvalue else 0 end) [2018-02],
sum(case when syear = 2018 and smonth = 3 then salesvalue else 0 end) [2018-03],
sum(case when syear = 2019 and smonth = 1 then salesvalue else 0 end) [2019-01],
sum(case when syear = 2019 and smonth = 2 then salesvalue else 0 end) [2019-02],
sum(case when syear = 2019 and smonth = 3 then salesvalue else 0 end) [2019-03]
from sales_history
group by brand_code
推荐阅读
- pandas - Pandas,根据条件将一个 DF 的一部分与另一个相乘
- php - 用户测试中多个客户端的 Symfony 4.4 弃用警告已弃用,但仍存在于文档中
- angular - Angular FormGroup无法读取未定义的属性'get'
- asp.net-core - 从 .Net Core 3 引用 .NET Framework DLL
- java - 哪种时间/日期类型用于什么?
- c++ - Visual Studio Code,C/C++ 扩展,包括重命名路径
- webdriverwait - OpenTest 是否支持隐式等待?
- asp.net - 我可以在没有 css 的情况下更改 asp.net 上按钮的形状吗?
- lambda - 节点js问题中的wordtonumber函数
- c - 在关键字之后标记任意字符串,直到 flex 中的行尾