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

后端 未结 6 1497
孤街浪徒
孤街浪徒 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:06

    I think the best way to do this is to create your own table with dates (you can also use master.dbo.spt_values, but I personally don't like that solution)

    declare @Temp_Dates table (CDate datetime)
    declare @Date datetime
    select @Date = (select min(CDate) from temp)
    
    while @Date <= (select max(CDate) from temp)
    begin
        insert into @Temp_Dates (CDate)
        select @Date
    
        select @Date = dateadd(dd, 1, @Date)
    end
    
    select D.CDate, isnull(T.id, 0) as id
    from @Temp_Dates as D
        left outer join temp as T on T.CDate = D.CDate
    

    you can also use recursive solution with CTE

提交回复
热议问题