SQL Server 2012-按月,3个月,6个月,11个月和上一年11个月分组

时间:2018-11-06 21:46:12

标签: sql group-by sql-server-2012 summary categorization

尝试构建一个查询,以按月,3个月,6个月,11个月和上一年11个月在销售列中显示总计。有什么可能的选择。 我尝试了datediff,但与日期相关的功能未得到预期的结果。

是否要提出一些建议?

1 个答案:

答案 0 :(得分:0)

这应该让您入门。

CREATE TABLE sales (
    product varchar (1),
    month int,
    amount int
)
insert into sales values ('a',1,5); insert into sales values ('a',1,33); 
insert into sales values ('a',2,32); insert into sales values ('b',1,12); 
insert into sales values ('b',2,4); insert into sales values ('c',1,5);
insert into sales values ('c',2,11);  insert into sales values ('c',2,13);

SELECT 
    product,
    SUM(CASE WHEN month = 1 THEN amount END) AS Month1,
    SUM(CASE WHEN month = 2 THEN amount END) AS Month2
FROM
    sales
GROUP BY
    product

output:

product   | Month1   |  Month2   
--------------------------------
    a     |   38     |   32   
    b     |   12     |   4
    c     |   5      |   24