2017-04-21 78 views
0

問題是這樣的,我有一個查詢返回日期和該特定日期的計數,但我想要的是不在該範圍內出現的日期(因爲不要不存在於表格中),但是具有零值。在零查詢的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年2月16日)的值,(2017年2月18日)和(2017-02-19)0值?

在此先感謝!

+1

這是你應該在調用SQL代碼做,像PHP或任何你在你的服務器上運行。它可以在SQL中完成,但是您需要另一個表格,每個日期在該範圍內都有一行。 –

回答

0

你可以用你需要這樣的所有日期生成輔助表:

select @rowNum := @rowNum +1, DATE_ADD('2017-02-21', INTERVAL [email protected] 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 

這是一個想法,我沒有測試它。

0

你可以解決它做的權利與具有這樣的日子一表連接:

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