如何在PostgreSQL中生成虚拟表以生成日期序列? [英] How to generate a virtual table to generate a sequence of dates in PostgreSQL?

查看:757
本文介绍了如何在PostgreSQL中生成虚拟表以生成日期序列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想生成一个日期列表,希望能与另一个表联接,但是我不知道使用什么语法,类似于以下内容:

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.date, transactions.account_id, transactions.amount
  FROM (...) as dates
       LEFT JOIN transactions ON transactions.date = dates.date
 WHERE dates.date >= '2010-01-01' AND dates.date <= '2010-12-31'
 ORDER BY dates.date;

我想要日期,因此无需在客户端进一步处理数据。我正在使用它来显示类似于此的表:

I want the dates so I don't have to further massage the data client-side. I'm using this to display a table similar to this:

Account    2010-01-01    2010-01-02    2010-01-03    Balance
============================================================
Chase 123        +100           -20           -70        +10
Chase 231                       +13            -9         +4


推荐答案

日期列表



使用 generate_series函数可以获取您要使用的数字列表可以添加日期以获取日期列表:

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);

结果:

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



透视



问题的后半部分处理结果集-将行数据转换为列数据。 PIVOT和UNPIVOT是ANSI,但我不认为它们是PostgreSQL当前支持的 / a>。枢纽查询的最一致支持的方法是使用聚合函数:

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



动态列



...表示动态SQL

这篇关于如何在PostgreSQL中生成虚拟表以生成日期序列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆