sql查询中的累积和(计算生产)

时间:2014-03-07 10:27:17

标签: sql sql-server

我有查询(下面)显示列中的数据,我需要累积生产

DATE      SHIFT  PRODUCTI SUM
1/1/2013  A      300      300
1/1/2013  B      301      601
1/1/2013  C      325      926
2/1/2013  A      568      1494
2/1/2013  B      256      1750
2/1/2013  C      580      2330
3/1/2013  A      645      2975
3/1/2013  B      235      3210
3/1/2013  C      236      3446

4 个答案:

答案 0 :(得分:1)

应该是 从表名

中选择总和(生产)

答案 1 :(得分:0)

试试这个:

SELECT t1.date, t1.shift, t1.production, 
(SELECT SUM(t2.production) from table t2
WHERE t2.date = t1.date AND t2.shift <= t1.shift 
OR t2.date < t1.date)
FROM table t1

告诉我它是否正常

Here you find your Sql Fiddle DEMO

答案 2 :(得分:0)

select t1.id, t1.PRODUCTION, SUM(t2.SomeNumt) as sum
from @t t1
inner join @t t2 on t1.id >= t2.id
group by t1.id, t1.SomeNumt
order by t1.id

答案 3 :(得分:0)

这只适用于sqlserver 2012 +

SELECT *, SUM(PRODUCTI) OVER (ORDER BY DATE, SHIFT) [SUM]
FROM @t