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

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

    You need a list of dates. The easiest way -- if you have data on each date, but just not for the where conditions -- is to use conditional aggregation:

    Select activity, cast(starttime as date) as date,
           SUM(case when activity = 'cricket' and email = 'abc'
                    then datediff(second, starttime, endtime))/60.0
                    else 0
               end) as TimePerDay
    from users
    where starttime >= dateadd(day, -15, last_update)
    group by activity, cast(starttime as date);
    

    Otherwise, if the dates are not in the table, then you need a list of dates. This can come from:

    • A calendar table.
    • A recursive CTE.
    • An explicit list in the query.

提交回复
热议问题