簡體   English   中英

查找具有條件的連續記錄

[英]Find consecutive records with criteria

我想編寫一個查詢,以為每個utilization_rate小於50 site查找連續的2個period s。

表:

ID Name    Period   Utilization_Rate
------------------------------------
1  Site 1  2014-R1  40
2  Site 1  2014-R2  30 
3  Site 1  2014-R3  25
4  Site 2  2014-R1  30
5  Site 2  2014-R2  20
6  Site 2  2014-R2  60
7  Site 3  2014-R2  30
8  Site 3  2014-R2  70
9  Site 3  2014-R2  40

預期結果:

ID Name    Period   Utilization_Rate
------------------------------------
1  Site 1  2014-R1  40
2  Site 1  2014-R2  30 
3  Site 1  2014-R3  25
4  Site 2  2014-R1  30
5  Site 2  2014-R2  20

這是戈登答案的OUTER APPLY版本:

SQL小提琴

SELECT t.*
FROM tbl t
OUTER APPLY(
    SELECT TOP 1 *
    FROM tbl
    WHERE 
        Name = t.Name
        AND ID < t.ID
    ORDER BY ID DESC
)p
OUTER APPLY(
    SELECT TOP 1 *
    FROM tbl
    WHERE
        Name = t.Name
        AND Id > t.ID
    ORDER BY ID ASC
)n
WHERE
    t.Utilization_Rate < 50
    AND (p.Utilization_Rate < 50 OR n.Utilization_Rate < 50)

我認為您希望所有兩對行(基於期間和站點)的利用率均低於50。

如果是這樣,您可以使用lead()lag()

select t.*
from (select t.*,
             lag(utilization_rate) over (partition by name order by period) as prev_ur,
             lead(utilization_rate) over (partition by name order by period) as next_ur,
      from tbl t
     ) t
where utilization_rate < 50 and (prev_ur < 50 or next_ur < 50);

這些功能在SQL Server 2012+中可用。 如果使用的是較早版本,則可以對相關子查詢或outer apply執行類似的操作。

SQL小提琴

使用普通舊聯接的相同查詢

select t.* from 
tbl t 
left join tbl tp on t.id-1=tp.id and t.name=tp.name
left join tbl tn on t.id+1=tn.id and t.name=tn.name
where t.utilization_rate < 50 and 
( 
  ISNULL(tp.utilization_rate,0) < 50 or ISNULL(tn.utilization_rate,0) < 50
)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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