假设我有一个包含两列的表,一个是int和一个布尔值。我需要在int列(阈值)中找到最小值,超过该值,布尔列中的所有值都为TRUE。如何构建此查询?
例如:
level | detection
-----------------
5 | False
6 | True
7 | False
8 | True
9 | True
10 | True
此特定场景应返回8级。
答案 0 :(得分:3)
试试这个,
Declare @Table table (level int,detection varchar(25))
insert into @Table values
(5,'False')
,(6,'True')
,(7,'False')
,(8,'True')
,(9,'True')
,(10,'True')
SELECT min(LEVEL) AS Threshold
FROM @Table
WHERE LEVEL > (
SELECT max(LEVEL)
FROM @Table
WHERE detection = 'False'
)
答案 1 :(得分:1)
一种可能的方式(online demo)。
WITH T
AS (SELECT *,
Prev = LEAD([detection]) OVER (ORDER BY [level] DESC),
CumeRowCount = SUM(1) OVER (ORDER BY [level] DESC
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW),
CumeTrueCount = SUM(CASE WHEN [detection] = 'True' THEN 1 END) OVER
(ORDER BY [level] DESC
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
FROM YourTable)
SELECT TOP 1 [level]
FROM T
WHERE CumeRowCount = CumeTrueCount /*All preceding and current rows must be true*/
AND Prev <> [detection] /* Next row not true*/
ORDER BY [level] DESC