如何在sql server 2012中根据年份计算运行总数

时间:2016-10-20 04:10:40

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

如何计算sql server 2012版本中的运行值。 这是我的样本数据。

CREATE TABLE #RollingTotalsExample
(
    [Date]     DATE PRIMARY KEY
    ,[Value]   INT
);

INSERT INTO #RollingTotalsExample
SELECT '2011-01-01',626
UNION ALL SELECT '2011-02-01',231 UNION ALL SELECT '2011-03-01',572
UNION ALL SELECT '2011-04-01',775
UNION ALL SELECT '2011-12-01',361 UNION ALL SELECT '2012-01-01',461
UNION ALL SELECT '2012-02-01',928 UNION ALL SELECT '2012-03-01',855
UNION ALL SELECT '2012-04-01',605  
UNION ALL SELECT '2012-12-01',26;

SELECT * FROM #RollingTotalsExample;

预期产出:

Date    Value   Runing Value
1/01/2011   626 626
1/02/2011   231 857
1/03/2011   572 1429
1/04/2011   775 2204
1/12/2011   361 2565
1/01/2012   461 461
1/02/2012   928 1389
1/03/2012   855 2244
1/04/2012   605 2849
1/12/2012   26  2875

应根据年份计算运行值。

2 个答案:

答案 0 :(得分:0)

使用窗口功能。 Year(Date)分区将在年度更改时重新开始运行总额,date订单将确保按日期计算总和。

SELECT Date, Value, 
SUM(Value) OVER (PARTITION BY YEAR(DATE) ORDER BY DATE) AS RunningValue
FROM #RollingTotalsExample

答案 1 :(得分:0)

我试过这个

SELECT A.DATE, A.VALUE, (SELECT SUM(B.VALUE)
                       FROM #ROLLINGTOTALSEXAMPLE B
                       WHERE B.DATE <= A.DATE) AS RUNING_TOTAL
FROM   #ROLLINGTOTALSEXAMPLE A
ORDER BY A.DATE;