Identify missing hours - find the gaps in time

强颜欢笑 提交于 2021-02-08 10:12:27

问题


I have a table with hours, but there are gaps. I need to find which are the missing hours.

select datehour
from stored_hours
order by 1;

The gaps in this timeline are easy to find:

select lag(datehour) over(order by datehour) since, datehour until
  , timestampdiff(hour, lag(datehour) over(order by datehour), datehour) - 1 missing
from stored_hours
qualify missing > 0

How can I create a list of the missing hours during these days?

(with Snowflake and SQL)


回答1:


To create a list/table of the missing hours:

  • Generate a list of all the hours between the min/max of the existing table.
  • To generate that list with Snowflake you will need to use session variables (as the generator only takes constants for the length.
  • Then find the missing hours with a left join, looking for nulls.

Use variables to find out the start and total number of hours:

set (min_hour, total_hours) = (
    select min(datehour) min_hour
        , timestampdiff('hour', min(datehour), max(datehour)) total_hours
    from stored_hours
);

Then do the left join with a generated table of all hours, to find the missing ones:

select generated_hour missing_hour
from ( -- generated hours
    select timestampadd('hour', row_number() over(order by 0), $min_hour) generated_hour
    from table(generator(rowcount => $total_hours))
) a
left outer join stored_hours b
on generated_hour=b.datehour
where datehour is null;

The result is a list of the missing hours:

(you could apply a similar technique for missing days, if the input are dates)



来源:https://stackoverflow.com/questions/65822975/identify-missing-hours-find-the-gaps-in-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!