基于日期的总和

时间:2017-07-28 13:50:48

标签: sql sql-server ssms

我目前有这个代码,我想根据年份对每个数量求和。我已经编写了一个代码,我认为它会在2016年和2017年汇总所有费用,但它没有正常运行。

我添加了两种不同类型的observables语句进行测试,看看是否有效,而且他们不会。当我把它们拿出来时,年度专栏只显示该特定收据的数量。

这是我目前的代码:

partition by

我希望我的数据看起来像这样

SELECT 
  ReceiptNumber
  ,Quantity
  ,Date
  ,sum(CASE WHEN (Date >= '2016-01-01' and Date < '2017-01-01') THEN 
        Quantity 
        ELSE 0 END)
        OVER (PARTITION BY Date) 
        as Annual2016
  ,sum(CASE WHEN (Date >= '2017-01-01' and Date < '2018-01-01') THEN 
        Quantity 
        ELSE 0 END) 
        OVER (PARTITION BY ReceiptNumber)
        as Annual2017
FROM Table1
GROUP BY ReceiptNumber, Quantity, Date

以下是我要提取的一些数据的示例:

ReceiptNumber    Quantity    Date           Annual2016    Annual2017
1                5           2016-01-05     17            13
2                11          2017-04-03     17            13
3                12          2016-11-11     17            13
4                2           2017-09-09     17            13

3 个答案:

答案 0 :(得分:3)

尝试这样的事情

Select 
..
sum(CASE WHEN (Date >= '2016-01-01' and Date < '2017-01-01') THEN 
        Quantity 
        ELSE 0 END)
        OVER () as Annual2016
sum(CASE WHEN (Date >= '2017-01-01' and Date < '2018-01-01') THEN 
        Quantity 
        ELSE 0 END)
        OVER ()as Annual2017
.. 
Where Date >= '2016-01-01' and Date < '2018-01-01'

答案 1 :(得分:1)

如果您希望它只在顶部打印一次,那么您应该在一个单独的查询中运行它,如:

SELECT YEAR(Date) y, sum(Quantity) s FROM Table1 GROUP BY YEAR(Date)

然后像这样执行主查询:

SELECT * FROM table1

容易,狡猾......; - )

您的原始问题也可以通过以下方式回答:

SELECT *, 
 (SELECT SUM(Quantity) FROM Table1 WHERE YEAR(Date)=2016 ) Annual2016,
 (SELECT SUM(Quantity) FROM Table1 WHERE YEAR(Date)=2017 ) Annual2017
FROM table1

答案 2 :(得分:0)

Window Aggregate 需要一些条件聚合。只需删除PARTITION BY,因为您已经过滤了CASE中的年份:

SELECT 
  ReceiptNumber
  ,Quantity
  ,Date
  ,sum(CASE WHEN (Date >= '2016-01-01' and Date < '2017-01-01') THEN 
        Quantity 
        ELSE 0 END)
        OVER () as Annual2016
  ,sum(CASE WHEN (Date >= '2017-01-01' and Date < '2018-01-01') THEN 
        Quantity 
        ELSE 0 END) 
        OVER () as Annual2017
FROM Table1

您可能不需要最终GROUP BY ReceiptNumber, Quantity, Date