sql return dates where there are no results

本小妞迷上赌 提交于 2019-12-11 14:03:11

问题


I want to get a table of results showing the dates that X has entries

SELECT count(*),
       date_column
FROM myTable
WHERE X
GROUP BY date_column
ORDER BY date_column DESC

This works, but I would also like to see the dates where X does not have entries, in my use case this would be intermediary dates.

So for instance 2013-3-10 would be in the results, but the next date would be 2013-3-5, yet I need my result to also return the days where count = 0, so in this case, the 6th, 7th, 8th and 9th

how would I format my query to include those extra times?


回答1:


I mocked up a simple example:

SELECT q.date_column, count(f.id) FROM
(SELECT
 generate_series(min(date_column),max(date_column), '1 day') AS date_column
 FROM mytable) AS q
LEFT JOIN mytable AS f
ON q.date_column=f.date_column
GROUP BY q.date_column ORDER BY q.date_column;

This generates all dates in the needed range. make sure not to do count(*) or you'll get 1 instead of 0 http://sqlfiddle.com/#!1/fd4ff/1




回答2:


The following works for postgresql:

SELECT count(*) as count, datecolumn as date FROM myTable group by datecolumn UNION 
select 0 as count, i::date as date from generate_series('2013-01-01', 
'2013-12-31', '1 day'::interval) i where i not in (select datecolumn from myTable) order by date desc


来源:https://stackoverflow.com/questions/15211408/sql-return-dates-where-there-are-no-results

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!