在SUM

时间:2016-02-24 16:27:37

标签: sql-server

我有一个SQL命令,它从1个表中汇总3列事件并插入到另一个表中。它根据需要正确地进行求和,但是在它插入的第二个表中,它保留了它总结的旧数据,是否有一种方法可以将它用来总结的数据删除并保留在表中?

以下是我使用的SQL命令:

INSERT INTO TotalIncidents([Name], IncA, IncB, IncC, DayOfData)
SELECT t.[Name], SUM(t.IncA), SUM(t.IncB), SUM(t.IncC), DATEADD(day, -1, GETDATE()) AS DayOfData
FROM TableA t
GROUP BY t.[Name]

我曾想过按行数使用删除命令,但我也注意到数据不一致意味着昨天的数据可以显示在顶部,然后前天的数据可以显示在底部,今天的数据可以显示在中间。也许我可以在命令的末尾添加一个order by语句来命令数据,然后在底部添加一个删除CTE命令,就像这样?

    INSERT INTO TotalIncidents([Name], IncA, IncB, IncC, DayOfData)
SELECT t.[Name], SUM(t.IncA), SUM(t.IncB), SUM(t.IncC), DATEADD(day, -1, GETDATE()) AS DayOfData
FROM TableA t
GROUP BY t.[Name] ORDER BY IncA, IncB, IncC Desc

WITH CTE AS
(
    SELECT *, ROW_NUMBER() OVER (PARTITION BY [Name] ORDER BY [Name]) AS RowNumber
    FROM TotalIncidents
    )
DELETE FROM CTE WHERE RowNumber > 1

但是,这确实是rownumbers,并不确定我是否应该沿着这条路走下去。任何帮助一如既往的赞赏。

示例数据:

NAME    |   IncA    |   IncB    |   IncC    |   Day
INC1        1           0           0           2016-01-03
INC1        0           2           0           2016-01-03
INC1        1           0           5           2016-01-03
INC1        1           7           3           2016-01-02

会改为

NAME    |   IncA    |   IncB    |   IncC    |   Day
INC1        3           9           8           2016-01-03

1 个答案:

答案 0 :(得分:0)

IF OBJECT_ID(N'tempdb..#tempIncidents') IS NOT NULL
BEGIN
    DROP TABLE #tempIncidents
END

SELECT  t.[Name],
        SUM(t.IncA) IncA,
        SUM(t.IncB) IncB,
        SUM(t.IncC) IncC,
        DATEADD(day,-1,GETDATE()) AS DayOfData
INTO    #tempIncidents
FROM    TotalIncidents t
GROUP BY t.[Name]
HAVING COUNT(t.[Name]) > 1


DELETE  FROM TotalIncidents
WHERE   [Name] IN (SELECT   [Name]
                   FROM     #tempIncidents)

INSERT  INTO TotalIncidents
        ([Name],
         IncA,
         IncB,
         IncC,
         DayOfData)
        SELECT  [Name],
                IncA,
                IncB,
                IncC,
                DayOfData
        FROM    #tempIncidents

这可以在事务内部完成,以防止因错误而导致数据丢失。