2011-09-21 59 views
1

我可以通過SQL Server數據庫中的列的總和來限制行嗎?如何通過總和來限制SQ​​L Server中的選擇?

例如:

Type | Time (in minutes) 
------------------------- 
A | 50 
B | 10 
C | 30 
D | 20 
E | 70 
... 

而且我想通過時間總和限制選擇。例如最多100分鐘。表格必須如下所示:

Type | Time (in minutes) 
------------------------- 
A | 50 
B | 10 
C | 30 

任何想法?謝謝。

回答

2
DECLARE @T TABLE 
(
[Type] CHAR(1) PRIMARY KEY, 
[Time] INT 
) 
INSERT INTO @T 
SELECT 'A',50 UNION ALL 
SELECT 'B',10 UNION ALL 
SELECT 'C',30 UNION ALL 
SELECT 'D',20 UNION ALL 
SELECT 'E',70; 


WITH RecursiveCTE 
AS  (
     SELECT TOP 1 [Type], [Time], CAST([Time] AS BIGINT) AS Total 
     FROM @T 
     ORDER BY [Type] 
     UNION ALL 
     SELECT R.[Type], R.[Time], R.Total 
     FROM (
       SELECT T.*, 
         T.[Time] + Total AS Total, 
         rn = ROW_NUMBER() OVER (ORDER BY T.[Type]) 
       FROM @T T 
       JOIN RecursiveCTE R 
         ON R.[Type] < T.[Type] 
       ) R 
     WHERE R.rn = 1 AND Total <= 100 
     ) 
SELECT [Type], [Time], Total 
FROM RecursiveCTE 
OPTION (MAXRECURSION 0); 

或者,如果你的表是小

SELECT t1.[Type], 
     t1.[Time], 
     SUM(t2.[Time]) 
FROM @T t1 
JOIN @T t2 
ON t2.[Type] <= t1.[Type] 
GROUP BY t1.[Type],t1.[Time] 
HAVING SUM(t2.[Time]) <=100 
+0

謝謝你的解決方案,這是好的,但我想知道,如果這個解決方案將與大量的行慢..? – EvanBlack

+1

@EvanBlack - 對於大量的行來說,兩者效率都很低,但是假設你有正確的索引以允許遞歸部分尋找並找到下一行,那麼CTE將會更好地擴展。它也不會最終處理** all **行,只是爲了返回一個子集,因爲連接查詢會。 [我的答案在這裏](http://stackoverflow.com/questions/7357516/subquery-or-leftjoin-with-group-by-which-one-is-faster/7454564#7454564)有一些表現統計或谷歌「運行總計SQL Server「來尋找大量的討論。 –