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

时间:2016-05-05 13:14:11

标签: sql-server-2008 running-total

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

---------------------------------------------------------
| Order No. | Order Total  | Running Total for Order No |
---------------------------------------------------------
|     1     | $10,000      | $10,000                    |
---------------------------------------------------------
|     1     | -$5,000      |  $5,000                    |
---------------------------------------------------------
|     1     |  $3,000      |  $8,000                    |
---------------------------------------------------------
|     2     |  $2,500      |  $2,500                    |
---------------------------------------------------------
|     2     |  $5,000      |  $7,500                    |
---------------------------------------------------------
|     2     |  $4,000      | $11,000                    |
---------------------------------------------------------

2 个答案:

答案 0 :(得分:0)

您需要遵循以下查询:

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

FROM price group by orderno

答案 1 :(得分:0)

我会这样做是Instead of Insert Trigger。触发器将从组的第一个值中减去/添加。显然,这应该在创建表时完成,但您可以在进行表更新后添加它。 请记住,为了使下面的代码有效,您需要在Order表上使用主键

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;