SHOW ALL Dates data between two dates; if no row exists for particular date then show zero in all columns

后端 未结 6 1500
孤街浪徒
孤街浪徒 2020-12-03 06:12

I want to show all dates between two dates when there is any date data missing then its should show zero in val column .

declare @temp table (
id int ident         


        
6条回答
  •  眼角桃花
    2020-12-03 07:01

    using a recursive cte with min and max

    declare @T table (id int identity(1,1) primary key, dt date not null, val int not null);
    insert into @T (dt, val) values 
           ('10/2/2012',1)
         , ('10/3/2012',1)
         , ('10/5/2012',1)
         , ('10/7/2012',2)
         , ('10/9/2012',2)
         , ('10/10/2012',2)
         , ('10/13/2012',2)
         , ('10/15/2012',2);
    --select * from @T;
    with cte as 
    ( select min(dt) as dt, max(dt) as mx 
      from @T 
      union all 
      select dateadd(dd, 1, dt), mx 
      from CTE 
      where dt < mx
    )
    select c.dt, isnull(t.val, 0) as val 
    from cte c
    left join @T t
    on c.dt = t.dt
    order by c.dt
    option (maxrecursion 0);
    
    dt         val
    ---------- -----------
    2012-10-02 1
    2012-10-03 1
    2012-10-04 0
    2012-10-05 1
    2012-10-06 0
    2012-10-07 2
    2012-10-08 0
    2012-10-09 2
    2012-10-10 2
    2012-10-11 0
    2012-10-12 0
    2012-10-13 2
    2012-10-14 0
    2012-10-15 2
    

提交回复
热议问题