【问题标题】:Rewrite sql query to pad empty month rows重写 sql 查询以填充空的月份行
【发布时间】:2018-02-06 23:15:08
【问题描述】:

我有这个查询,用于在我们自己的跟踪系统中获取博客的统计信息。

我在 2 个表上使用联合选择,因为我们每天在 1 个表中汇总数据并将今天的数据保存在另一个表中。

我想要显示最近 10 个月的流量。这个查询可以做到这一点,但是在特定月份没有流量,该行不在结果中。

我以前在 mysql 中使用过一个日历表来避免这种情况,但我根本不擅长重写这个查询来加入那个日历表。

日历表有一个名为“datefield”的字段,我的日期格式为 YYY-MM-DD

这是我当前使用的查询

SELECT FORMAT(SUM(`count`),0) as `count`, DATE(`date`) as `date` 
FROM
(
  SELECT  count(distinct(uniq_id)) as `count`, `timestamp` as `date`
  FROM    tracking
  WHERE   `timestamp`  > now() - INTERVAL 1 DAY AND target_bid = 92
  group by `datestamp`

  UNION ALL

 select sum(`count`),`datestamp` as `date`
  from aggregate_visits
  where `datestamp` > now() -  interval 10 month
  and target_bid = 92
  group by `datestamp`
 ) a
GROUP BY MONTH(date)

【问题讨论】:

    标签: mysql date join


    【解决方案1】:

    这样的?

     select sum(COALESCE(t.`count`,0)),s.date as `date`
     from DateTable s
     LEFT JOIN (SELECT * FROM aggregate_visits 
                where `datestamp` > now() -  interval 10 month
                and target_bid = 92) t
      ON(s.date = t.datestamp)
     group by s.date
    

    【讨论】:

    • 工作就像一个魅力,从你的例子中稍微重写......非常感谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-04
    • 1970-01-01
    相关资源
    最近更新 更多