sql选择运行总计

时间:2015-08-31 09:54:30

标签: sql sql-server

请帮助解决此问题

我想按date1分组,然后按日期升序排序并使用累积结果更新RunningTotal字段

到目前为止,这就是我所拥有的

CREATE TABLE dbo.RunningTotal (
    date1 date    
    ,Entry int
    ,RunningTotal int
)

INSERT INTO dbo.RunningTotal (date1,Entry,RunningTotal)VALUES('2015-01-03',100,NULL)
INSERT INTO dbo.RunningTotal (date1,Entry,RunningTotal)VALUES('2015-02-03',200,NULL)
INSERT INTO dbo.RunningTotal (date1,Entry,RunningTotal)VALUES('2015-05-03',300,NULL)
INSERT INTO dbo.RunningTotal (date1,Entry,RunningTotal)VALUES('2015-07-13',400,NULL)
INSERT INTO dbo.RunningTotal (date1,Entry,RunningTotal)VALUES('2015-01-03',-500,NULL)

UPDATE dbo.RunningTotal
SET RunningTotal = RT2.RunningTotal
FROM dbo.RunningTotal RT1
INNER JOIN (
    SELECT 
        Entry
        ,(SELECT SUM(Entry) FROM dbo.RunningTotal WHERE Entry <= rt.Entry) As RunningTotal
    FROM dbo.RunningTotal rt
) RT2
ON RT1.Entry = RT2.Entry

SELECT * FROM dbo.RunningTotal

但是在这个选择中我没有考虑日期和分组

感谢!!!

2 个答案:

答案 0 :(得分:1)

您的查询存在多个问题。关联子句需要跟踪日期,表名必须是FROM子句中的别名。

UPDATE toupdate
    SET RunningTotal = RT.RunningTotal
FROM dbo.RunningTotal toupdate INNER JOIN
     (SELECT rt.*
             (SELECT SUM(rt2.Entry)
              FROM dbo.RunningTotal rt2
              WHERE rt2.date1 <= toupdate.date1
             ) As RunningTotal
      FROM dbo.RunningTotal rt
     ) RT
     ON toupdate.date1 = rt.date1;

当日期相同时,您没有指定要执行的操作。

答案 1 :(得分:0)

由于您可能希望在插入新记录后更新运行总计,因此使用触发器执行此操作是有意义的。下面是一些简单的SQL来创建一个触发器来执行此操作。

CREATE TRIGGER UpdateRunningTotal   ON  dbo.RunningTotal
AFTER INSERT 
AS 
BEGIN

DECLARE @date DATE, @total INT
--get the date of the insert record
SET @date = (SELECT date1 from inserted)
--get the total for that date
SET @total = (SELECT SUM(Entry) FROM dbo.RunningTotal WHERE dbo.RunningTotal.date1 = @date)
--update all records with new running total
UPDATE dbo.RunningTotal SET dbo.RunningTotal.RunningTotal = @total WHERE  dbo.RunningTotal.date1 = @date

END
GO