SQL query that returns all dates not used in a table

后端 未结 4 1016
一个人的身影
一个人的身影 2020-12-18 10:44

So lets say I have some records that look like:

2011-01-01 Cat
2011-01-02 Dog
2011-01-04 Horse
2011-01-06 Lion

How can I construct a query

4条回答
  •  天涯浪人
    2020-12-18 10:57

    You're right — SQL does not make it easy to identify missing data. The usual technique is to join your sequence (with gaps) against a complete sequence, and select those elements in the latter sequence without a corresponding partner in your data.

    So, @BenHoffstein's suggestion to maintain a permanent date table is a good one.

    Short of that, you can dynamically create that date range with an integers table. Assuming the integers table has a column i with numbers at least 0 – 13, and that your table has its date column named datestamp:

       SELECT candidate_date AS missing
         FROM (SELECT CURRENT_DATE + INTERVAL i DAY AS candidate_date
                 FROM integers
                WHERE i < 14) AS next_two_weeks
    LEFT JOIN my_table ON candidate_date = datestamp
        WHERE datestamp is NULL;
    

提交回复
热议问题