![](/img/trans.png)
[英]find all rows whose one column belongs to the same value and also another column satisfy a condition on SQL server 2008
[英]SQL query to find smallest value above which all values in another column satisfy some condition
說我有一個包含兩列的表,一個int和一個布爾值。 我需要在int列(閾值)中找到最小值,在該最小值上方,布爾列中的所有值均為TRUE。 如何構造此查詢?
例如:
level | detection
-----------------
5 | False
6 | True
7 | False
8 | True
9 | True
10 | True
對於此特定的場景,應該返回8級。
這樣嘗試
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'
)
一種可能的方式( 在線演示 )。
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.