generate_series() method fails in Redshift

前端 未结 7 1474
时光说笑
时光说笑 2020-11-27 22:01

When I run the SQL Query:

 select generate_series(0,g)
 from ( select date(date1) - date(date2) as g from mytable ;

It returns an error:

7条回答
  •  鱼传尺愫
    2020-11-27 22:35

    Why it's not working was explained above. Still, the question "what can we do about this?" is open.

    If you develop a BI system on any platform (with generators supported or not), it is very handy to have dimension tables with sequences of numbers and dates. How can you create one in Redshift?

    1. in Postgres, produce the necessary sequence using generator
    2. export to CSV
    3. create a table with the same schema in Redshift
    4. import the CSV from Step 2 to Redshift

    Imagine you have created a very simple table called calendar:

     id, date
     1, 2017-01-01
     2, 2017-01-02
     ..., ...
     xxx, 2020-01-01
    

    So your query will look like this:

    SELECT t.id, t.date_1, t.date_2, c.id as date_id, c.date
    FROM mytable t
    JOIN calendar c
    ON c.date BETWEEN t.date_1::date AND t.date_2::date
    ORDER BY 1,4
    

    In calendar table you can also have first dates of week, month, quarter, weekdays (Mon,Tue,etc.), which makes such table super effective for time-based aggregations.

提交回复
热议问题