填写mysql查询范围中缺少的日期

时间:2016-04-11 20:32:29

标签: mysql oracle gaps-and-islands

我有以下查询:

select date(updated_at) as data, COUNT(id) as numar 
from `coupons`
where `user_id` = 5 and `won_by` != 0 and `updated_at` >= '2016-04-01'
group by DAY(updated_at), month(updated_at), year(updated_at)

结果如下:

2016-04-01-   229
2016-04-03-   30
2016-04-04-   6
2016-04-07-   1
2016-04-08-   1
2016-04-10-   1

我可以做些什么来接收这样的事情:

2016-04-01-   229
2016-04-02-   0
2016-04-03-   30
2016-04-04-   6
2016-04-05-   0
2016-04-06-   0
2016-04-07-   1
2016-04-08-   1
2016-04-10-   1

1 个答案:

答案 0 :(得分:1)

我发现这样做的最好方法是简单地创建(并维护)具有单个列的辅助表,其中包含您关心的所有日期。类似的东西:

CREATE TABLE date_join(     date date not null主键   );

然后以任何方便的方式插入每个日期的记录(手动,如果它是一次性的,作为日常过程的一部分,通过存储过程等)。

此时,它只是date_join和初始查询的左连接,使用CASE语句将NULL转换为0:

SELECT dj.date, q.numar
  FROM      date_join dj
  LEFT JOIN (select date(updated_at) as date, COUNT(id) as numar 
               from `coupons`
              where `user_id` = 5 and `won_by` != 0 and `updated_at` >= '2016-04-01'
              group by DATE(updated_at)
            ) q
         ON dj.date = q.date
   ORDER BY dj.date;