从第一个日期开始的每个日期的SQL查询SUM

时间:2016-04-27 21:52:25

标签: sql sql-server sql-server-2008

我到处都搜索过,这让我发疯了。我们说我有两个字段:actiondate和qty。以下是数据样本:

  actiondate        qty
  4/22/2016          2
  4/23/2016          7
  4/23/2016          4
  4/25/2016          9
  4/26/2016          6
  4/26/2016          3
  4/26/2016          4

我想对行动日期进行分组,并将qty从开头日期加总,如下所示:

  actiondate       qty
  4/22/2016         2
  4/23/2016         13
  4/25/2016         22
  4/26/2016         35

我真诚地感谢任何人的帮助。

2 个答案:

答案 0 :(得分:1)

在SQL Server 2012 +中:

SELECT  actiondate,
        SUM(total) OVER (ORDER BY actiondate) running_total
FROM    (
        SELECT  actiondate, SUM(qty) total
        FROM    mytable
        GROUP BY
                actiondate
        ) q

在SQL Server 2008中:

WITH    q AS
        (
        SELECT  actiondate,
                SUM(qty) total
        FROM    mytable
        GROUP BY
                actiondate
        )
SELECT  q1.actiondate, SUM(q2.total)
FROM    q q1
JOIN    q q2
ON      q2.actiondate <= q1.actiondate
GROUP BY
        q1.actiondate

答案 1 :(得分:1)

这是快速版:

select actiondate, (
    select sum(qty)
    from table t2
    where t2.actiondate <= t1.actiondate) as qty
from table t1
group by actiondate