在两个日期之间显示所有日期数据; 如果特定日期不存在行,则在所有列中显示零

rah*_*rma 5 sql t-sql sql-server

我想显示两个日期之间的所有日期,当有任何日期数据缺失时,它应该在val列中显示为零.

declare @temp table (
id int identity(1,1) not null,
CDate smalldatetime ,
val int
)
Run Code Online (Sandbox Code Playgroud)

插入数据以检查数据

insert into @temp select '10/2/2012',1
insert into @temp select '10/3/2012',1
insert into @temp select '10/5/2012',1
insert into @temp select '10/7/2012',2
insert into @temp select '10/9/2012',2
insert into @temp select '10/10/2012',2
insert into @temp select '10/13/2012',2
insert into @temp select '10/15/2012',2
Run Code Online (Sandbox Code Playgroud)

在每月的第一天和今天之间检索记录

select * from @temp where CDate between '10/01/2012' AND '10/15/2012'
Run Code Online (Sandbox Code Playgroud)

当我运行此查询时,它显示这两个日期之间的所有数据,但我还想包括缺少日期 val=0

带有示例数据的SQL FIDDLE

Ric*_*iwi 10

;with d(date) as (
  select cast('10/01/2012' as datetime)
  union all
  select date+1
  from d
  where date < '10/15/2012'
  )
select t.ID, d.date CDate, isnull(t.val, 0) val
from d
left join temp t
       on t.CDate = d.date
order by d.date
OPTION (MAXRECURSION 0) -- use this if your dates are >99 days apart
Run Code Online (Sandbox Code Playgroud)

你需要弥补日期,所以我在这里使用递归公用表表达式. SQL小提琴

MAXRECURSION编号

指定此查询允许的最大递归数.number是0到32767之间的非负整数.指定0时,不应用限制.如果未指定此选项,则服务器的默认限制为100.

在查询执行期间达到MAXRECURSION限制的指定或默认数量时,查询结束并返回错误.