如何使用 SQL 服务器存储过程显示一个月中缺少的几天甚至不在数据库中

How to display missing days of the month even is not on the database using SQL Server stored procedure

我需要显示一份显示一个月中所有日期的报告。假设从 2020 年 1 月 1 日到 2020 年 1 月 31 日。为了做到这一点,我创建了一个具有开始日期和最后日期的存储过程,并使用带 table

的 Left Join

我写了

DECLARE @FromDate DATE = '2020-01-01';
DECLARE @FromDate DATE = '2020-01-31';

SELECT a1.f1, a1.f2, b.f3. b.f5
FROM table1
LEFT JOIN table2 AS b ON b.f1 = a.f1
                      AND (@FromDate IS NULL OR a.Date >= @FromDate)
                      AND (@ToDate IS NULL OR a.Date <= @ToDate)

结果,如2020-01-02等缺失天数无记录为

2020-01-01 f1 f2
2020-01-04 f1 f2

我需要显示所有日期,所以结果将是

    2020-01-01 f1 f2
    2020-01-02 f1 f2
    2020-01-03 null null
    2020-01-04 f1 f2
    2020-01-05 null null
    .
    .
    2020-01-31 null null

我使用微软SQL服务器

您可以使用递归查询生成日期,然后将 table 与 left join 相结合。

with recursive all_dates as (
    select @FromDate dt
    union all 
    select dateadd(day, 1, dt) from all_dates where dt < @ToDate
)
select d.dt, t.f1, t.f2
from all_dates d
left join table1 on t.date = d.date

我不明白 table2 有什么用,因为您的查询 returns 列仅来自 table1,所以我从查询中删除了 if。

如果您需要生成超过 100 天的周期,那么您可能需要在查询的最后添加 option (maxrecursion 0)

您需要生成所需的日期。如果你有一个 table,它看起来像:

with dates as (
      select @startdate as dte
      union all
      select dateadd(day, 1, dte)
      from dates
      where dte < @enddate
     )
select d.dte, t1.f1, t1.f2
from dates d cross join
     table1 t1;