每个不同ID的累计金额

时间:2016-01-13 21:20:20

标签: sql sql-server tsql

我有这样的表:

   TypeA   TypeSize
    110       2
    110       2
    110       6
    200       5
    200       7
    301       1
    301       2
    301       5
    301       1

并且想要总结每行的累积大小,但仅针对相同的Type。所以我会得到这样的东西:

   TypeA   TypeSize  Csize
    110       2        2
    110       2        4
    110       6        10
    200       5        5
    200       7        12
    301       1        1
    301       2        3
    301       5        8
    301       1        9

累积金额很好用:

SUM(CAST(TypeSize AS bigint)) OVER(ORDER BY TypeA ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS Csize

所以问题是,现在我得到了所有类型的完整累积总和。它看起来不像第二个输出。

我必须以某种方式GROUP BY TypeA。但是如何以及在哪里 - 我首先想到的是每个(对于每个不同类型的每个或迭代我的SUM选择)

    For Each TypeA:
    SELECT *,
    SUM(CAST(TypeSize AS bigint)) 
          OVER(ORDER BY TypeA ROWS BETWEEN 
          UNBOUNDED PRECEDING AND CURRENT ROW) 
          AS Csize
    FROM Table

但对于这个简短的sql,我真的需要一个big for each like here posted吗?

有什么建议吗?谢谢

2 个答案:

答案 0 :(得分:2)

这是我的解决方案:

你几乎只需要PARTITION BY

CREATE TABLE #temp (TypeA int ,  TypeSize int )

INSERT INTO  #temp (TypeA ,  TypeSize)
 VALUES (   110  ,     2),
   ( 110  ,     2),
   ( 110   ,    6),
   ( 200    ,   5),
   ( 200    ,   7),
   ( 301    ,   1),
   ( 301    ,   2),
   ( 301    ,   5),
   ( 301    ,   1)

   SELECT TypeA ,  TypeSize, SUM(CAST(TypeSize AS bigint)) OVER(PARTITION BY TypeA  ORDER BY TypeA ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS Csize FROM #temp AS A  

结果:

enter image description here

答案 1 :(得分:0)

对于那些在2005年并且不能使用前面和当前行无界限的行:

with cte
as
(
select *,row_number() over (partition by typea order by typea) as rn
from #temp
)
select typea,typesize,(select sum(typesize) from cte t1 where t1.rn<t2.rn+1 and t1.typea=t2.typea
group by typea
) as cszie
from cte t2