2017-08-29 47 views
1

我有这个查询我用来获取我们自己的跟踪系统中的博客统计数据。重写sql查询以填充空的月份行

我使用union select over 2表,因为我们每天在1个表中汇总数据,并将今天的数据保留在另一个表中。

我想拥有最近10个月的流量显示。此查询确实如此,但是在特定月份中没有流量不在结果中。

我以前在mysql中使用过日历表来加入反对,以避免这种情况,但即时通讯根本没有熟练的enoght重写此查询以加入该日历表。

的calendart表有1场名为 “的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) 

回答

2

像这样的事情?

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 
+0

工作就像一个魅力与你的例子重写一点..非常感谢 –