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

后端 未结 7 1721
甜味超标
甜味超标 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:19

    Try this. You can generate the missing dates in a union by using the existing CTE as a basis for Row_Number()

    ;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
    from cte
    where starttime >= dateadd(day, -15, last_update)
    group by activity, cast(starttime as date)
    UNION ALL
    Select 'cricket' activity, everyday.[date], 0
    FROM 
    (
        select top 1000 dateadd(day,row_number() OVER (order by starttime),(select cast(min(starttime) as date) from CTE)) [date]
        from CTE
    ) everyday
    WHERE everyday.[date] NOT IN (SELECT cast(starttime as date) FROM CTE)
    AND everyday.[date] < (SELECT cast(max(starttime) as date) from CTE)
    ORDER BY date
    

提交回复
热议问题