[英]Optimizing select count query if number of matching rows greater than number
[英]PostgreSQL: Select rows greater than a value by a number of consecutive times
我有下表:
id updated_on ch1
1 2020-03-23 08:30:25 90.577
2 2020-03-23 08:30:55 99.213
3 2020-03-23 08:31:05 101.426
4 2020-03-23 08:31:15 103.457
5 2020-03-23 08:31:25 103.982
6 2020-03-23 08:31:35 101.742
7 2020-03-23 08:31:45 97.983
8 2020-03-23 08:32:15 90.091
9 2020-03-23 08:41:35 96.985
10 2020-03-23 08:41:45 99.468
11 2020-03-23 08:41:55 101.714
12 2020-03-23 08:42:05 103.66
13 2020-03-23 08:42:15 104.388
14 2020-03-23 08:42:25 105.12
15 2020-03-23 08:42:35 106.737
16 2020-03-23 08:42:45 108.19
17 2020-03-23 08:42:55 109.626
18 2020-03-23 08:43:05 110.91
我需要選擇 ch1 大於 100 且連續 5 次以上的第一行。 在上表中:
我開始使用以下代碼:
SELECT id, updated_on, ch1, CASE WHEN ch1>100 THEN 1 ELSE 0 END greater FROM table order by updated_on
但我不知道如何從這里繼續。
您可以使用窗口函數來解決這個間隙和孤島問題。
您將首先構建具有窗口計數的值大於100
的連續記錄組。 然后,枚舉每組中的行,最后過濾每組的第五條記錄。
select id, updated_on, ch1
from (
select
t.*,
row_number() over(partition by grp order by updated_on) rn
from (
select
t.*,
count(*) filter(where ch1 <= 100) over(
order by updated_on
rows between unbounded preceding and 1 preceding
) grp
from mytable t
) t
) t
where ch1 > 100 and rn = 5
id | updated_on | ch1 -: | :------------------ | ------: 15 | 2020-03-23 08:42:35 | 106.737
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.