【问题标题】:Repeat Rows Between Date Values in RedshiftRedshift 中日期值之间的重复行
【发布时间】:2019-08-30 07:56:24
【问题描述】:

我有一张桌子:

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_dateend_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 中实现这一点?

【问题讨论】:

    标签: sql amazon-web-services amazon-redshift


    【解决方案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;
    

    Demo

    注意:对于 Redshift,请使用 DATE_PART(year, t2.start_date),其中 datetime 组件不采用单引号。

    【讨论】:

    • 谢谢你,这行得通!测试和工作。如果不明确指定日历表中的年份,我怎么能做到这一点?我的第一个想法是WITH years AS ( SELECT generate_series(2014, 2018, 1) AS year ),但我在 Redshift 中遇到错误:INFO: Function "generate_series(integer,integer,integer)" not supported. Query 1 ERROR: ERROR: Specified types or functions (one per INFO message) not supported on Redshift tables.
    • 从错误消息中可以看出,generate_series 在 Redshift 上不可用,它基于 Postgres 的旧分支。如果您想朝那个方向发展,请在 Redshift 中搜索生成系列。
    • 在 Redshift 中生成系列的一个众所周知的技巧是从不同的表中进行选择,例如。 SELECT row_number() over () + 2000 as year from arbitrary_table limit 25 会给你一系列的2001 - 2026。它有点原始,但很有魅力。
    猜你喜欢
    • 1970-01-01
    • 2013-04-27
    • 1970-01-01
    • 1970-01-01
    • 2016-11-26
    • 1970-01-01
    • 1970-01-01
    • 2018-03-16
    • 1970-01-01
    相关资源
    最近更新 更多