【问题标题】:Sum the column value incrementally with the same ID column使用相同的 ID 列递增地对列值求和
【发布时间】:2013-05-14 04:47:55
【问题描述】:

我在 SQL Server 2008 中查询时遇到问题,我在 Internet 上进行了搜索,但一无所获,或者它没有给我任何关于如何操作的想法。

使用 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

【问题讨论】:

  • 我也很好奇如何在不使用临时表存储中间和的情况下解决这个问题。
  • 什么数据库? Oracle 可以轻松做到这一点,MSSQL 2012 也可以

标签: sql sql-server-2008


【解决方案1】:

请检查:

;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

【讨论】:

  • 哇!它有效!...非常感谢@techdo。 . .我在这里学习...谢谢,祝你有美好的一天......
【解决方案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

【讨论】:

  • -1,不正确。他想按顺序对具有相同 ID 的行求和,而不是连续的ID。
猜你喜欢
  • 2018-04-12
  • 1970-01-01
  • 1970-01-01
  • 2015-12-03
  • 1970-01-01
  • 2021-01-18
  • 2021-02-08
  • 2013-05-17
  • 2011-07-22
相关资源
最近更新 更多