如何计算按订单号分组的 运行 总数

How to calculate running total grouped by Order No

尝试在 SQL Server 2008 中为订单创建 运行 总计,类似于下面的 table(我的 SQL 中存在订单号和订单总计列服务器 table),尝试使用递归 cte,但我的结果是所有订单的总数 运行,没有按订单号分组。关于如何将 运行 总计按订单号分组的任何建议?谢谢

---------------------------------------------------------
| Order No. | Order Total  | Running Total for Order No |
---------------------------------------------------------
|     1     | ,000      | ,000                    |
---------------------------------------------------------
|     1     | -,000      |  ,000                    |
---------------------------------------------------------
|     1     |  ,000      |  ,000                    |
---------------------------------------------------------
|     2     |  ,500      |  ,500                    |
---------------------------------------------------------
|     2     |  ,000      |  ,500                    |
---------------------------------------------------------
|     2     |  ,000      | ,000                    |
---------------------------------------------------------

您需要进行以下查询:

    SELECT orderno,
SUM((CASE WHEN ISNUMERIC(ordertotal)=1
THEN CONVERT(MONEY,ordertotal) ELSE 0 END)
)
AS [Converted to Numeric]

FROM price group by orderno

我会用 Instead of Insert Trigger 来做到这一点。触发器将从组的第一个值中 subtract/add。显然,这应该在创建 table 时完成,但您可以在 table 更新后添加它。 请记住,为了使下面的代码起作用,您需要在订单 table

上有一个主键
CREATE TABLE Orders
(
           id           INT IDENTITY(0, 1) PRIMARY KEY
         , orderNo      INT
         , orderTotal   MONEY
         , runningTotal MONEY
);

INSERT INTO Orders
VALUES
(1,10000,10000),
(1,-5000,5000),
(1,3000,8000),
(2,2500,2500),
(2,5000,7500),
(2,4000,11500);

GO

--CREATE TRIGGER

CREATE TRIGGER trg_RunningTotal ON Orders
INSTEAD OF INSERT
AS
    BEGIN
        DECLARE @PreviousTotal MONEY =
              (
              SELECT TOP 1
                    a.runningTotal
                    FROM  Orders AS a
                        INNER JOIN INSERTED AS b ON a.orderNo = b.orderNo
                    WHERE a.orderno = b.Orderno
                    ORDER BY a.id DESC
              );
        INSERT INTO Orders
        SELECT
             orderno,
             orderTotal,
             (@PreviousTotal + orderTotal) AS runningTotal
             FROM INSERTED;
    END;

--Insert new record

        INSERT INTO orders
        VALUES
        (1,1000,NULL);

--View newly added record

        SELECT
             *
             FROM  orders
             WHERE orderno = 1;