我有一张桌子:
id | start_date | end_date
----------------------------
01 | 2016-02-19 | 2017-03-02
02 | 2017-06-19 | 2018-09-11
03 | 2015-03-19 | 2018-05-02
04 | 2018-02-19 | 2018-01-05
05 | 2014-06-19 | 2018-07-25
,我想基于start_date
和end_date
之间的时间重复行,在这种情况下,是根据从这两个日期列中提取的年份进行的。我想要的结果类似于:
id | year
=========
01 | 2016
01 | 2017
02 | 2017
02 | 2018
03 | 2015
03 | 2016
03 | 2017
03 | 2018
04 | 2018
05 | 2014
05 | 2015
05 | 2016
05 | 2017
05 | 2018
如何在Redshift中实现这一目标?
答案 0 :(得分:1)
我们可以尝试加入包含所有年份的日历表:
WITH years AS (
SELECT 2014 AS year UNION ALL
SELECT 2015 UNION ALL
SELECT 2016 UNION ALL
SELECT 2017 UNION ALL
SELECT 2018
)
SELECT
t2.id,
t1.year
FROM years t1
INNER JOIN yourTable t2
ON t1.year BETWEEN DATE_PART('year', t2.start_date) AND DATE_PART('year', t2.end_date)
ORDER BY
t2.id,
t1.year;
注意:对于日期时间部分不使用单引号的Redshift,请使用DATE_PART(year, t2.start_date)
。