【问题标题】:How to create multiple rows from a single row in Redshift SQL如何从 Redshift SQL 中的单行创建多行
【发布时间】:2020-02-14 18:51:05
【问题描述】:

我想根据 AWS Redshift 中表中的列将表中的单行扩展到多行。

这是我的示例表架构和行:

CREATE TABLE test (
  start timestamp, -- start time of the first slot
  slot_length int, -- the length of the slots in minutes
  repeat int       -- how many slots will be there
);

INSERT INTO test (start, slot_length, repeat) VALUES
('2019-09-22T00:00:00', 90, 2),
('2019-09-21T15:30:00', 60, 3);

我想根据“重复”列的值将这两行扩展为 5。所以任何行都会被扩展“重复”次数。第一次扩展不会改变任何东西。后续扩展需要在“start”列中添加“slot_length”。这是我最后想要的行的最终列表:

'2019-09-22 00:00:00', 90, 2  -- expanded from the first row 
'2019-09-22 01:30:00', 90, 2  -- expanded from the first row
'2019-09-21 15:30:00', 60, 3  -- expanded from the second row
'2019-09-21 16:30:00', 60, 3  -- expanded from the second row
'2019-09-21 17:30:00', 60, 3  -- expanded from the second row

这可以通过 Redshift 中的纯 SQL 来完成吗?

【问题讨论】:

标签: amazon-redshift


【解决方案1】:

此 SQL 应该可以解决您的目的。如果是,请投票。

    select t.start
    , case when rpt.repeat>1 
           then dateadd(min,t.slot_length*(rpt.repeat-1),t.start) 
           else t.start 
           end as new_start
    , t.slot_length
    , t.repeat
    from schema.test t
    join (select row_number() over() as repeat from schema.random_table) rpt
    on t.repeat>=rpt.repeat
    order by t.slot_length desc,rpt.repeat;

请注意,架构中的“random_table”行数应至少与“repeat”列中的最大值一样多。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-08-17
    • 2019-04-06
    • 2023-02-02
    • 2013-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多