【问题标题】:List dates from specific mysql table and return 0 if day does not exists列出特定 mysql 表中的日期,如果日期不存在则返回 0
【发布时间】:2020-11-04 21:11:33
【问题描述】:

我正在尝试从一个查询中生成一个结果,该查询列出了从今天(2020 年 7 月 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

我已经找到了一种从here 生成日历日期并根据我的需要进行调整的方法,但我不知道如何将结果与我的表格结合起来。

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

如有任何帮助,敬请期待。

【问题讨论】:

    标签: mysql sql date sum recursive-query


    【解决方案1】:

    一个选项使用递归查询 - 在 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
    

    【讨论】:

    • 嗨,使用您的第二个建议,当我添加 where 子句来过滤代码(其中代码 = 123)时,它只返回与代码匹配的日期。无论如何要调整这个?谢谢
    • @nfn:将过滤器移动到join的on子句:left join mytable t on t.day = current_date - interval d.n day and t.code = 123
    猜你喜欢
    • 1970-01-01
    • 2016-02-22
    • 1970-01-01
    • 2020-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-06
    相关资源
    最近更新 更多