How to generate all dates between two dates

半世苍凉 提交于 2019-11-26 21:39:29

问题


How can I retrieve all dates between '2015-10-02' to '2015-11-02' in SQLite? (String type) Result will be like:

'2015-10-03'
'2015-10-04'
'2015-10-05'
...
'2015-11-01'

This is not a question about SELECT * FROM myTable where myDate <= '2015-01-01' AND myDate >= '2015-01-31'. This is not about selecting all existing records which have a field between two days. I just want to retrieve all possible date values between two dates. I want to use them to query the count of record by days.

Date             Count
'2015-01-01'      19
'2015-01-02'      10
'2015-01-03'      0
...

回答1:


This is not possible without a recursive common table expression, which was introduced in SQLite 3.8.3:

WITH RECURSIVE dates(date) AS (
  VALUES('2015-10-03')
  UNION ALL
  SELECT date(date, '+1 day')
  FROM dates
  WHERE date < '2015-11-01'
)
SELECT date FROM dates;



回答2:


If your date column is already a date type with the format YYYY-MM-DD then you can use the following query:

SELECT date_field AS Date, COUNT(date_field)
FROM table
WHERE (date_field BETWEEN '2015-10-02' AND '2015-11-02')
GROUP BY date_field

If the date column is actually a string, then you can use the strftime() function:

SELECT date_field AS Date, COUNT(date_field)
FROM table
WHERE strftime('%Y-%m-%d', date_field) BETWEEN '2015-10-02' AND '2015-11-02'
GROUP BY date_field


来源:https://stackoverflow.com/questions/32982372/how-to-generate-all-dates-between-two-dates

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