我有一些这样的行:
avg_income | date_from | date_to
------------+------------+------------
1256.9 | 2016-11-21 | 2017-07-10
4383.2 | 2017-05-06 | 2017-06-01
Run Code Online (Sandbox Code Playgroud)
我想将这些avg_income
值投影到相应的月份,如下所示:
avg_income | month
------------+------------
1256.9 | 2016-11-01
1256.9 | 2016-12-01
1256.9 | 2017-01-01
1256.9 | 2017-02-01
1256.9 | 2017-03-01
1256.9 | 2017-04-01
1256.9 | 2017-05-01
1256.9 | 2017-06-01
1256.9 | 2017-07-01
4383.2 | 2017-05-01
4383.2 | 2017-06-01
Run Code Online (Sandbox Code Playgroud)
到目前为止,我刚刚提出了一个可怕的问题,FOR/LOOP/generate_series(...)
所以我想知道有没有更优雅(和有效)的方法来做到这一点?
您可以generate_series()
为此使用。
select t.avg_income, d.month
from the_table t
cross join lateral (
select g.m::date as month
from generate_series(date_trunc('month', t.date_from), date_trunc('month', t.date_to), interval '1 month') as g (m)
) as d
order by t.avg_income, d.month;
Run Code Online (Sandbox Code Playgroud)
或者:
select t.avg_income, d.month::date
from the_table t
cross join lateral generate_series(date_trunc('month', t.date_from), date_trunc('month', t.date_to), interval '1 month') as d (month)
order by t.avg_income, d.month;
Run Code Online (Sandbox Code Playgroud)
在线示例:http : //rextester.com/ADG4243
归档时间: |
|
查看次数: |
65 次 |
最近记录: |