2015-11-05 40 views
5

我有一個表中有下列內容:每n選擇行做我的SQL Server數據庫的SUM

Date  | Amount 
------------|---------- 
2012-12-17 | 9.00 
2012-12-18 | 8.00 
2012-12-19 | 0.00 
2012-12-20 | 1.50 
2012-12-21 | 2.50 
2012-12-22 | 0.00 
2012-12-23 | 0.00 
2012-12-24 | 0.00 
2012-12-25 | 0.00 
2012-12-26 | 4.00 
2012-12-27 | 2.00 
2012-12-28 | 7.00 

我想要做的就是採取每選擇3行SUMAmount。如果SUM的總數爲0,則應刪除這3條記錄。否則,它應該讓他們獨自一人,並採取接下來的3條記錄,並進行相同的檢查。

所以在這種情況下,只有以下三條記錄應從表格中刪除,因爲它們是SUM導致0的唯一的記錄。

2012-12-23 | 0.00 
2012-12-24 | 0.00 
2012-12-25 | 0.00 

我該如何在SQL Server中做他?

回答

6

您可以使用ROW_NUMBER來製作3個元素組和calucalte sum。

WITH cte AS 
(
    SELECT *, rn = (ROW_NUMBER() OVER(ORDER BY [Date]) - 1)/3 
    FROM #tab 
), cte2 AS 
(
    SELECT *, [sum] = SUM(Amount) OVER (PARTITION BY rn ORDER BY [Date]) 
    FROM cte 
) 
SELECT * 
FROM cte2 
WHERE [sum] = 0; 

LiveDemo

而且隨着DELETE

WITH cte AS 
(
    SELECT *, rn = (ROW_NUMBER() OVER(ORDER BY [Date]) - 1)/3 
    FROM #tab 
), cte2 AS 
(
    SELECT *, [sum] = SUM(Amount) OVER (PARTITION BY rn ORDER BY [Date]) 
    FROM cte 
) 
DELETE t 
FROM #tab t 
JOIN cte2 c 
    ON t.[Date] = c.[Date] 
WHERE [sum] = 0; 

SELECT * 
FROM #tab; 

LiveDemo2

編輯:

如果您的數據可以包含負值,你可以使用:

WITH cte AS 
(
    SELECT *, rn = (ROW_NUMBER() OVER(ORDER BY [Date]) - 1)/3 
    FROM #tab 
), cte2 AS 
(
    SELECT rn, [sum] = SUM(Amount) 
    FROM cte 
    GROUP BY rn 
) 
SELECT c.* 
FROM cte c 
JOIN cte2 c2 
    ON c.rn = c2.rn 
WHERE [sum] = 0; 

LiveDemo3

+0

這隻能如果它發生了3倍連續的金額= 0落入一個分區組,假設我理解 – Mihai

+0

@Mihai的問題See updated – lad2025