列出特定mysql表中的日期,如果日期不存在,则返回0

vjhs03f7  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(385)

我试图从一个查询中生成一个结果,该查询列出了从今天(2020/07/15)开始的最后7天以及与特定代码匹配的视图。如果当天代码没有视图,我希望当天返回0。
表格格式

DAY    | CODE | VIEWS
2020-07-10 | 123  | 5
2020-07-11 | 123  | 2
2020-07-12 | 123  | 3
2020-07-15 | 123  | 8
2020-07-15 | 124  | 2
2020-07-15 | 125  | 2

代码123的预期结果

DAY    | VIEWS
2020-07-09 | 0
2020-07-10 | 5
2020-07-11 | 2
2020-07-12 | 3
2020-07-13 | 0
2020-07-14 | 0
2020-07-15 | 8

我已经找到了从这里生成日历日期并根据需要进行调整的方法,但是我不知道如何将结果与我的表连接起来。

select * from 
  (select 
    adddate(NOW() - INTERVAL 7 DAY, t0) day 
    from   
      (select 1 t0 
       union select 1 
       union select 2 
       union select 3 
       union select 4 
       union select 5 
       union select 6 
       union select 7) t0) v

任何帮助都是必须的。

h7appiyu

h7appiyu1#

一个选项使用递归查询—在mysql 8.0中提供:

with recursive cte as (
    select current_date - interval 6 day dt
    union all
    select dt + interval 1 day from cte where dt < current_date
)
select c.dt, coalesce(sum(t.views), 0) views
from cte
left join mytable t on t.day = c.dt
group by c.dt
order by c.dt

您还可以手动构建派生表,正如您最初打算的那样(这将适用于所有版本的mysql):

select current_date - interval d.n day dt, coalesce(sum(t.views), 0) views
from (
    select 0 n 
    union all select 1 
    union all select 2
    union all select 3
    union all select 4
    union all select 5
    union all select 6
) d
left join mytable t on t.day = current_date - interval d.n day
group by d.n
order by d.n desc

相关问题