SQL 查询查找 3 条连续记录和相关数据

SQL 查询查找 3 条连续记录和相关数据

需要选择值> = 0.7并且连续出现至少3次的数据

            hourly recorded per day
Hours         00    0100  0200   0300   0400   0500 
ValueNumber   .7    .8    .5     .4     .8     .85     so on

问题是我可以选择> = 0.7 且出现 3 次但不连续的数据。任何帮助都非常感谢。

select distinct  encounterId, COUNT(valueNumber) 
FROM table pta 
where interventionId in (2201,2202)
  and pta.valueNumber >=0.7
  and pta.valueNumber is not null
group by encounterId 
having COUNT(hours)>=3

如果您需要更多信息,请询问。数据库非常庞大,每一列都记录为“InterventionID”。以上是搜索条件,完成后我可以将其放入临时表中,然后提取记录。期待某种解决方案。

谢谢

答案1

WITH cte AS ( SELECT series,
                     date_time,
                     value, 
                     LEAD(value) OVER (PARTITION BY series 
                                       ORDER BY date_time) lead1, 
                     LEAD(value, 2) OVER (PARTITION BY series 
                                          ORDER BY date_time) lead2
              FROM datatable 
              WHERE value >= 0.7 )
SELECT series, date_time, value
FROM cte
WHERE lead1 >= 0.7
  AND lead2 >= 0.7

如果没有系列,则将其从字段集和 PARTITION BY 子句中删除。

相关内容