SQLite query to join on a range of dates?

后端 未结 3 424
别跟我提以往
别跟我提以往 2021-01-25 07:55

I am working with SQLite.

Suppose I have a table sales with two columns, date and count, to keep track of how many glasses of lemo

3条回答
  •  自闭症患者
    2021-01-25 08:52

    You could use a Recursive Common Table expression to generate a series of dates and join to it:

    WITH RECURSIVE
      cnt(x) AS (
        SELECT 0
        UNION ALL
        SELECT x+1 FROM cnt
        LIMIT (SELECT ((julianday('2010-01-10') - julianday('2010-01-04'))) + 1)
    ), 
    WITH date_series AS (
      SELECT date(julianday('2010-01-04'), '+' || x || ' days') as date 
    FROM date_series ds
    )
    SELECT AVG(COALESCE(s.count, 0)) as avg_sales_count
    FROM date_series ds
      LEFT JOIN sales s ON ds.date = s.date
    

    I wrote a blog post with more info here: http://www.geekytidbits.com/generate-date-range-sqlite/

提交回复
热议问题