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

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

    First You have to generate the Date series with a query like this:

    -- Generate 15 past days name from now
    set @n:=date(now() + interval 1 day);
    select (select @n:= @n - interval 1 day) day_series from users  limit 15;
    

    and then join select with date_series. for null values you can use COALESCE:

    SELECT q2.day_series as days , COALESCE(TimePerDay, 0) as TPD from Your_select q1
    right join (
        -- select date_series
    ) as q2
    on q1.Timestamp = q2.day_series and .... 
    

    --- final Query based on my understanding from 1st query

    set @n:=date(now() + interval 1 day);
    SELECT activity
    ,cast(starttime AS DATE) AS q1_DATE
    ,COALESCE(SUM(datediff(second, starttime, endtime)) / 60.0, 0) AS TimePerDay
    FROM (
        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
        ) q1
    RIGHT JOIN (
        SELECT (
                SELECT @n: = @n - interval 1 day
                ) day_series
        FROM users limit 15
        ) q2 ON q1.q1_DATE = q2.day_series
    WHERE starttime >= dateadd(day, - 15, last_update)
    GROUP BY activity
        ,cast(starttime AS DATE);
    

提交回复
热议问题