使用零值在mysql查询上添加缺少的行

时间:2017-04-21 17:44:53

标签: mysql

问题是这样,我有一个查询返回该特定日期的日期和计数,但我想要的是那个未出现在该范围内的日期(因为表中不存在),但是零值。

我的疑问是:

     SELECT fechacierre, COUNT(idcliente) as cantidad
     FROM cliente
     WHERE fechacierre BETWEEN DATE_ADD('2017-02-21', INTERVAL -6 DAY) AND '2017-02-21'
     GROUP BY fechacierre

给出这个结果:

------------------------
fechacierre | cantidad
------------------------
2017-02-15  | 3
------------------------
2017-02-17  | 1
------------------------
2017-02-20  | 3
------------------------
2017-02-21  | 2
------------------------

如何获取(2017-02-16),(2017-02-18)和(2017-02-19)的值为0的值?

提前致谢!

2 个答案:

答案 0 :(得分:0)

您可以生成一个包含所需日期的辅助表,如下所示:

select @rowNum := @rowNum +1, DATE_ADD('2017-02-21', INTERVAL -@rownum DAY) as fechacierre from Any_table_with_some_records, (select @rowNum := 0) t

然后你可以加入

SELECT fechacierre, COUNT(idcliente) as cantidad
FROM cliente
RIGHT JOIN aux ON aux.fechacierre = cliente.fechacierre
WHERE fechacierre BETWEEN DATE_ADD('2017-02-21', INTERVAL -6 DAY) AND '2017-02-21'
     GROUP BY fechacierre

这是一个想法,我没有测试它。

答案 1 :(得分:0)

您可以使用具有以下所有日期的表来解决它与RIGHT JOIN:

SELECT fechacierre, COUNT(idcliente) as cantidad
     FROM cliente RIGHT JOIN (select * from 
(select adddate('1970-01-01',t4.i*10000 + t3.i*1000 + t2.i*100 + t1.i*10 + t0.i) selected_date from
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t0,
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t1,
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t2,
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t3,
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t4) v
where selected_date between DATE_ADD('2017-02-21', INTERVAL -6 DAY) and '2017-02-21') t ON fechacierre = selected_date
     WHERE fechacierre BETWEEN DATE_ADD('2017-02-21', INTERVAL -6 DAY) AND '2017-02-21'
     GROUP BY fechacierre