我是 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
关于像 PEPSI 这样的 SQL SERVER PIVOT 按年划分,然后按月份划分等。(请参阅附图以获得清晰的想法),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59895328/