如何生成虚拟表以在PostgreSQL中生成日期序列?
技术问答
177 人阅读
|
0 人回复
|
2023-09-14
|
我想生成一个日期列表,希望能与另一个表连接,但是我不知道要使用什么语法,类似于以下内容:" d' I$ ~9 P. ]# O
SELECT dates.date, transactions.account_id, transactions.amount
3 J4 c6 x2 p" O: z. a, y FROM (...) as dates
+ O V% H! ]. W- d LEFT JOIN transactions ON transactions.date = dates.date
( m) d7 H7 N0 q5 N WHERE dates.date >= '2010-01-01' AND dates.date 我想要日期,因此不必在客户端进一步处理数据。我正在使用它来显示类似于此的表:
4 C. ^# V9 h4 B( @! PAccount 2010-01-01 2010-01-02 2010-01-03 Balance
$ t1 @8 o+ f4 \$ A/ N {! s============================================================
5 |* e9 A @2 T& ^4 h: JChase 123 +100 -20 -70 +10% d3 J+ x* _" g$ _5 c1 I
Chase 231 +13 -9 +4 @0 z' A: S. W, I7 }
/ E2 D9 |. H1 O- F0 U- ~( V解决方案:6 Y+ x7 E0 h1 [+ C" S; _
, p, Q u2 l: N4 V
) p" ?+ _$ Q8 p% f7 I* q. ]7 G
* B4 G' o6 [; a8 w Z3 l 日期清单+ y, u! {" ?/ m
使用generate_series函数获取可以添加到日期的数字列表,以获取日期列表:; F3 {: _0 e+ e V4 x8 D' r2 o
SELECT CURRENT_DATE + s.a AS dates 2 z/ Y1 _+ G' g) u8 z4 b+ e3 N- d( E
FROM generate_series(0,14,7) as s(a);
+ B+ n! k# _1 P6 D1 u结果:- ^! V. Q3 J2 n' |3 |% j
dates
; j/ D& @& M* o. M8 z------------
% x/ r( H- I/ b& y& s2 _2004-02-059 G2 [, G- p7 n( v% X( h# U6 ?
2004-02-12+ k6 l# A1 p5 Z% v+ P2 }
2004-02-19" A. j$ _( p4 _5 U& W j
旋转
0 \: A- ^6 b J m# l! Q8 h9 x问题的后半部分涉及透视结果集-0 }" [- m$ g7 p. N
将行数据转换为列数据。PIVOT和UNPIVOT是ANSI,但我目前不认为它们受PostgreSQL支持。枢纽查询的最一致支持的方法是使用聚合函数:0 U' M; s7 r5 e) C+ {, m
SELECT t.account,7 X" n0 v* l% N; E, T
SUM(CASE WHEN t.date = '2010-01-01' THEN t.amount END) AS '2010-01-01',) _0 p2 c8 I% Z, f5 p- R- l5 u
SUM(CASE WHEN t.date = '2010-01-02' THEN t.amount END) AS '2010-01-02'," H- D1 g; Z5 z' L: G/ [6 h1 ~
SUM(CASE WHEN t.date = '2010-01-03' THEN t.amount END) AS '2010-01-03',
/ G, s, q& f7 ]# c# {9 l1 s D; g SUM(t.amount) AS Balance
4 y4 ?8 d7 [: x) H& b9 Z5 S FROM (SELECT CURRENT_DATE + s.a AS dates % C2 M# Z- g/ s c6 g" m
FROM generate_series(0,14,7) as s(a)) x& X1 J j/ ~8 t5 s/ q ]' }
LEFT JOIN TRANSACTIONS y ON y.date = x.date, I% x2 d! T0 Z, `
GROUP BY t.account; g& N2 L+ s. c H, ]9 Q
动态栏
* y/ F" Z7 f' p8 a3 j…表示动态SQL。 |
|
|
|
|
|