簡體   English   中英

SQL查詢以查找最小值,高於該最小值的另一列中的所有值均滿足某些條件

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM