如何在 PostgreSQL 中生成虚拟表来生成日期序列?
我想生成一个日期列表,希望与另一个表连接,但我不知道要使用什么语法,类似于:
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;
我想要日期,这样我就不必进一步处理数据客户端。我用它来显示与此类似的表格:
Account 2010-01-01 2010-01-02 2010-01-03 Balance
============================================================
Chase 123 +100 -20 -70 +10
Chase 231 +13 -9 +4
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
日期列表
使用 generate_series 函数 获取数字列表您可以将其添加到日期中以获取日期列表:
结果:
透视
问题的后一部分涉及透视结果集 - 将行数据转换为列数据。 PIVOT 和 UNPIVOT 是 ANSI,但我不认为它们目前受 PostgreSQL 支持< /a>.最一致支持的旋转查询方法是使用聚合函数:
动态列
...意味着 动态 SQL。
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:
Result:
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:
Dynamic Columns
...means dynamic SQL.