首页 > 解决方案 > 像百事可乐这样的 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 

在此处输入图像描述

使用上面的查询,我得到了附件中的输出

[请查看我正在尝试的所需输出的附件以及我使用上述查询获得的输出]

标签: sqlsql-servertsqlgroup-bypivot

解决方案


我会为此使用条件聚合:

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

推荐阅读