How to extend the query to add 0 in the cell when no activity is performed

后端 未结 7 1559
甜味超标
甜味超标 2020-12-21 09:57

I have the following query, it is working fine to show the cricket time played per day. All I need is to show 0 when no cricket is played. At the moment it is skipping those

相关标签:
7条回答
  • 2020-12-21 10:33

    Try this

    ;WITH CTE AS (
    SELECT email, last_update, activity, starttime, endtime, duration as [Totaltime] from users 
    WHERE activity='cricket' and email='abc'
    GROUP BY email, activity, duration, starttime, endtime, last_update
    )
    select activity, cast(starttime as date) as date,
    SUM(datediff(second, starttime, endtime))/60.0 as TimePerDay
    into #tempcte
    from CTE
    --where starttime >= dateadd(day, -15, last_update)
    group by activity, cast(starttime as date)
    
    select * from #tempcte
    
    DECLARE @startDate date = (select min([date]) from #tempcte)
    DECLARE @endDate date = (select max([date]) from #tempcte)
    ;WITH dates(Date) AS 
    (
        SELECT @startdate as Date
        UNION ALL
        SELECT DATEADD(d,1,dates.Date)
        FROM dates 
        WHERE dates.Date < @enddate --and dates.Date not in (select [date] from #tempcte)
    )
    --select * from dates
    Select activity, [date], TimePerDay
    from #tempcte
    union
    select 'cricket' activity, [Date] as Date, 0 as TimePerDay FROM dates where dates.Date not in (select [date] from #tempcte)
    
    drop table #tempcte
    
    0 讨论(0)
提交回复
热议问题