【问题标题】:How best can I to pivot my redshift table?我怎样才能最好地旋转我的红移表?
【发布时间】:2021-04-26 11:28:40
【问题描述】:

我有一个名为 metadata 的 Redshift 表,其中包含以下列:

id key value
1001 code1 my value
1001 code2 another
1001 code3 yet another
1002 code1 new one
1002 code2 here
1002 code3 last
1003 code1 hello
1003 code2 goodbye
1004 code2 now
1004 code3 then

我想要一个返回如下的查询:

id code1 code2 code3
1001 my value another yet another
1002 new one here last
1003 hello goodbye
1004 now then

请注意,并非所有 ID 都包含全部 3 个代码。有些会有 1 或 2 个,有些会全部 3 个,还有一些仍然没有。

【问题讨论】:

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


    【解决方案1】:

    您可以使用条件聚合。假设您知道结果集中需要的列,您可以使用:

    select id,
           max(case when key = 'code1' then value end) as code1,
           max(case when key = 'code2' then value end) as code2,
           max(case when key = 'code3' then value end) as code3
    from t
    group by id;
    

    如果您不知道具体的值并需要从数据中读取它们。 . .这更棘手。据我所知,Redshift 不支持动态 SQL。因此,您需要在数据库中查询不同的 key 值,并使用您喜欢的语言将查询构造为字符串。然后您可以执行该查询。

    【讨论】:

    • 谢谢 - 我意识到我没有包含其他需求/用例。可能有也可能没有所有三个“代码”列,或者它们的任意组合,或者有时根本没有。所以一行可能有全部 3 个,另一行只有 code1 和 code2,另一行可能没有。
    • @BenShichman 。 . .你应该问一个新问题。在回答完此问题后更改此问题只会使正确答案无效。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-23
    • 1970-01-01
    相关资源
    最近更新 更多