像 PEPSI 这样的 SQL SERVER PIVOT 按年划分,然后按月份划分等。(请参阅附图以获得清晰的想法)

标签 sql sql-server t-sql group-by 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 

enter image description here

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

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

最佳答案

我会为此使用条件聚合:

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/

相关文章:

c# - 在 SQL Server 上跟踪 View

SQL 大小写选择

sql - 如何在Sql Server中查找相邻记录中具有相同值的记录? (我相信正确的术语是一个区域??)

t-sql - 如何防止此 SQL 中发生死锁

python - 绑定(bind) SQL 数量不正确

sql - 警告 SQL71502 - 过程 <名称> 具有对对象 <名称> 的未解析引用

mysql - 如何将空间数据插入包含道路列的表中

sql-server - 获取ID日期和正负天数之间的日期

javascript - 如何从 asp 页面将表的内容或 sql 查询的结果发送到剪贴板?

php - Codeigniter 内部的迁移