如何根据两个日期从表中的日期列中获取缺少的日期

时间:2018-03-27 15:01:27

标签: mysql sql

我有一个表名作为'记录'字段是' date',如何使用MySQL查询传递两个日期(例如2018-03-23,2018-03-30)来获取表中缺少的日期

记录:

id  dates
------------
1   2018-03-23
2   2018-03-24
3   2018-03-27
4   2018-03-28
5   2018-03-30

预期结果缺少日期:25,26,29

2 个答案:

答案 0 :(得分:0)

请查看以下示例:

CREATE TABLE #tmp (
    my_date DATETIME
)

INSERT INTO #tmp (my_date) VALUES ('2016-01-01')
INSERT INTO #tmp (my_date) VALUES ('2016-01-02')
INSERT INTO #tmp (my_date) VALUES ('2016-01-04')
INSERT INTO #tmp (my_date) VALUES ('2016-01-05')
INSERT INTO #tmp (my_date) VALUES ('2016-01-07')
INSERT INTO #tmp (my_date) VALUES ('2016-01-08')
INSERT INTO #tmp (my_date) VALUES ('2016-01-10')
INSERT INTO #tmp (my_date) VALUES ('2016-01-11')

DECLARE @max_date DATETIME
SELECT @max_date = max(my_date) FROM #tmp

SELECT DATEADD(day,1,t1.my_date) as miss_date
FROM #tmp t1 
LEFT JOIN #tmp t2 ON t1.my_date=DATEADD(day,-1,t2.my_date)
WHERE t2.my_date is null 
  AND t1.my_date<>@max_date

另请参阅:MySQL: Find Missing Dates Between a Date Range

答案 1 :(得分:0)

这是一个SQL Server解决方案

    declare @date datetime=(Select min(date) from table)
    declare @maxdate datetime = (Select max(date) from table)

    while @date<=@maxdate
    begin
    if @date not in (Select date from table)
    select @date

    select @date=dateadd(dd, 1, @date)
    end