日期:2014-05-18 浏览次数:20514 次
DECLARE @T TABLE( 列1 VARCHAR(10),列2 INT,列3 VARCHAR(10),列4 VARCHAR(10) ) INSERT @T SELECT 'a', 10, '15:59:30', 'N' UNION ALL SELECT 'a', 20, '15:59:29', 'D' UNION ALL SELECT 'b', 20, '15:59:29', 'D' UNION ALL SELECT 'a', 10, '15:59:29', 'D' UNION ALL SELECT 'b', 15, '15:59:20', 'N' UNION ALL SELECT 'c', 25, '15:58:30', 'D' UNION ALL SELECT 'b', 10, '15:58:30', 'N' UNION ALL SELECT 'c', 10, '15:58:30', 'D' UNION ALL SELECT 'a', 20, '15:58:00', 'D' UNION ALL SELECT 'b', 5, '15:57:50', 'D' --添加数据 INSERT @T SELECT 'a', 10, '15:59:31', 'D' UNION ALL SELECT 'a', 20, '15:59:32', 'D' UNION ALL SELECT 'a', 15, '15:59:33', 'D' UNION ALL SELECT 'C', 15, '15:59:33', 'N' UNION ALL SELECT 'C', 50, '15:59:34', 'D' UNION ALL SELECT 'B', 30, '15:59:34', 'D' ;WITH CTE AS ( SELECT *,ROW_NUMBER() OVER(PARTITION BY [列1] ORDER BY [列3]) AS NUM FROM @T ) SELECT B.[列1],SUM(B.列2) AS [列2],MIN(B.列3) AS [列3] FROM CTE A,CTE B WHERE A.[列1] = B.[列1] AND A.[列4] = 'D' AND B.[列4] = 'D' AND A.NUM <= B.NUM AND NOT EXISTS ( SELECT 1 FROM CTE WHERE [列1] = A.[列1] AND NUM > A.NUM AND NUM < B.NUM AND [列4] <> 'D' ) AND NOT EXISTS ( SELECT 1 FROM CTE WHERE [列1] = A.[列1] AND NUM = A.NUM - 1 AND [列4] = 'D' ) GROUP BY B.[列1],A.NUM HAVING SUM(B.列2) >= 40 --结果 列1 列2 列3 a 50 15:58:00 a 45 15:59:31 b 50 15:59:29 C 50 15:59:34