Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
770 views
in Technique[技术] by (71.8m points)

sqlite - How to generate all dates between two dates

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
...
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...