使用相同的ID列递增地对列值求和

时间:2013-05-14 04:47:55

标签: sql sql-server-2008

我在查询SQL Server 2008时遇到了麻烦,我在互联网上搜索但没有发现任何内容,或者它没有给我任何关于如何操作的想法。

使用Northwind数据库,我需要查询表OrderDetails并选择OrderID和UnitPrice,显示类似这样的内容,

OrderID   -    UnitPrice
------------------------
10248     -     14.00
10248     -     9.80
10248     -     34.80
10249     -     18.60

结果应该是:

OrderID   -    UnitPrice
------------------------
10248     -     14.00
10248     -     23.80
10248     -     58.6
10249     -     18.60

2 个答案:

答案 0 :(得分:5)

请检查:

;with T as(
    select 
        *, 
        ROW_NUMBER() over (partition by OrderID order by OrderID) RNum
    from YourTable
)
select 
    *, 
    (select sum(UnitPrice) from T b where b.OrderID=a.OrderID and b.RNum<=a.RNum) CumTotal
From T a

试试SQL Fiddle

答案 1 :(得分:-2)

可以参考以下内容:

SELECT t1.id,
       t1.unitprice,
       SUM(t2.unitprice) AS SUM
FROM t t1
INNER JOIN t t2 ON t1.id >= t2.id
GROUP BY t1.id,
         t1.unitprice
ORDER BY t1.id

<强>演示:

SQLFIDDLE DEMO