SQL总和和上一行

时间:2019-07-19 09:15:25

标签: sql sql-server select group-by sum

我有下表:

________________________
date        |  amount
________________________
01-01-2019  | 10
01-01-2019  | 10
01-01-2019  | 10
01-01-2019  | 10
02-01-2019  |  5
02-01-2019  |  5
02-01-2019  |  5
02-01-2019  |  5
03-01-2019  | 20
03-01-2019  | 20

这些是按日期排列的突变值。我希望我的查询按日期返回总金额。所以对于02-01-2019,我需要40(4乘10)+ 20(4乘5)。对于2019年3月1日,我需要(4乘10)+ 20(4乘5)+ 40(2乘20)等等。一个查询有可能吗?我该如何实现?

我当前的查询以获取单个突变:

Select s.date,
  Sum(s.amount) As Sum_amount
From dbo.Financieel As s
Group By s.date

3 个答案:

答案 0 :(得分:1)

您可以在下面尝试-

DEMO

select dateval,
SUM(amt) OVER(ORDER BY dateval ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as amt
from
(
    SELECT 
    dateval, 
    SUM(amount) amt
FROM t2  group by dateval
)A

输出:

dateval              amt
01/01/2019 00:00:00  40
01/02/2019 00:00:00  60
01/03/2019 00:00:00  100

答案 1 :(得分:0)

我建议使用窗口功能,例如:

select date, sum(amount) over( order by date)
from table

答案 2 :(得分:0)

尝试以下脚本以获取所需的输出-

SELECT A.date,
(SELECT SUM(amount) FROM <your_table> WHERE Date <= A.Date) C_Total
FROM <your_table> A
GROUP BY date
ORDER BY date

输出为-

date        C_Total
01-01-2019  40
02-01-2019  60
03-01-2019  100