如何通过列的总和限制SQL Server中的选择?

时间:2011-09-21 09:46:54

标签: sql-server-2005

我可以通过SQL 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

有什么想法吗?感谢。

1 个答案:

答案 0 :(得分: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