SELECT SUM(missing_dates) AS num_missing
FROM (
SELECT GREATEST("DATE" - LAG("DATE") OVER (ORDER BY "DATE") - 1, 0)
AS missing_dates
FROM table_name
);
其中,对于示例数据:
CREATE TABLE table_name ("DATE") AS
SELECT DATE '2020-01-01' FROM DUAL UNION ALL
SELECT DATE '2020-01-02' FROM DUAL UNION ALL
SELECT DATE '2020-01-03' FROM DUAL UNION ALL
SELECT DATE '2020-01-05' FROM DUAL UNION ALL
SELECT DATE '2020-01-06' FROM DUAL UNION ALL
SELECT DATE '2020-01-07' FROM DUAL UNION ALL
SELECT DATE '2020-01-08' FROM DUAL UNION ALL
SELECT DATE '2020-01-10' FROM DUAL;
2条答案
按热度按时间nue99wik1#
https://dbfiddle.uk/cSKZloYA
(max(date) - min(date) + 1)
将给予范围内的总天数。count(distinct date)
将是表中现有(不同)天数。两者之间的差异是不存在的天数。
注意:
date
是保留字,因此如果它是实际列名,则必须使用"date"
分隔。(https://en.wikipedia.org/wiki/List_of_SQL_reserved_words)hwamh0ep2#
您可以使用
LAG
分析函数来查找前一个日期,然后计算出相差的天数,如果相差大于1,则缺少的天数为1天:其中,对于示例数据:
输出:
| 数量_缺失|
| - ------|
| 第二章|
fiddle