How to generate a virtual table to generate a sequence of dates in PostgreSQL?

前端 未结 1 814
走了就别回头了
走了就别回头了 2021-02-14 01:25

I\'d like to generate a list of dates with the hopes of joining with another table, but I don\'t know what syntax to use, something similar to this:

SELECT dates         


        
相关标签:
1条回答
  • 2021-02-14 02:16

    List of Dates

    Use the generate_series function to get a list of numbers that you can add to a date in order to get a list of dates:

    SELECT CURRENT_DATE + s.a AS dates 
      FROM generate_series(0,14,7) as s(a);
    

    Result:

    dates
    ------------
    2004-02-05
    2004-02-12
    2004-02-19
    

    Pivoting

    The latter part of your question deals with pivoting the result set -- converting row data into columnar data. PIVOT and UNPIVOT are ANSI, but I don't see them as supported by PostgreSQL currently. The most consistently supported means of pivoting a query is to use aggregate functions:

       SELECT t.account,
              SUM(CASE WHEN t.date = '2010-01-01' THEN t.amount END) AS '2010-01-01',
              SUM(CASE WHEN t.date = '2010-01-02' THEN t.amount END) AS '2010-01-02',
              SUM(CASE WHEN t.date = '2010-01-03' THEN t.amount END) AS '2010-01-03',
              SUM(t.amount) AS Balance
         FROM (SELECT CURRENT_DATE + s.a AS dates 
                 FROM generate_series(0,14,7) as s(a)) x
    LEFT JOIN TRANSACTIONS y ON y.date = x.date
     GROUP BY t.account
    

    Dynamic Columns

    ...means dynamic SQL.

    0 讨论(0)
提交回复
热议问题