【问题标题】:AWS ATHENA Transpose Columns into RowsAWS ATHENA 将列转置为行
【发布时间】:2021-02-02 08:49:13
【问题描述】:

我有一个 csv 文件上传到一个 S3 存储桶,我使用 AWS Glue 获取该存储桶,然后使用 Athena 进行查询。 CSV 表格式如下:

Item Country Category 2017 2018 2019 2020
Item1 CA Network 128 129 130 129
Item2 CA Desktop 128 129 130 129
Item3 CA Apps 128 129 130 129

我想将该格式转换为:

Item Country Category Year Value
Item1 CA Network 2017 128
Item1 CA Network 2018 129
Item1 CA Network 2019 130
Item1 CA Network 2020 129
Item2 CA Desktop 2017 128
Item2 CA Desktop 2018 129
Item2 CA Desktop 2019 130
Item2 CA Desktop 2020 129
Item3 CA Apps 2017 128
Item3 CA Apps 2018 129
Item3 CA Apps 2019 130
Item3 CA Apps 2020 129

如何在 Athena 中使用 SQL 来实现这一点?

我试过了,但它对我不起作用: Simple way to transpose columns and rows in SQL?

感谢任何帮助。谢谢!

【问题讨论】:

    标签: sql amazon-athena


    【解决方案1】:

    Union all 在这里提供了一个选项:

    SELECT Item, Country, Category, 2017 AS Year, "2017" AS Value FROM yourTable
    UNION ALL
    SELECT Item, Country, Category, 2018, "2018" FROM yourTable
    UNION ALL
    SELECT Item, Country, Category, 2019, "2019" FROM yourTable
    UNION ALL
    SELECT Item, Country, Category, 2020, "2020" FROM yourTable
    ORDER BY Item, Country, Category, Year, Value;
    

    这种方法具有动态年数列的稳健性。但是话又说回来,无论如何你都不应该使用那个设计,因为它没有标准化。因此,希望您可以使用上面的查询,或者它的一个轻微变体,让您的数据在预期输出中出现规范化。

    【讨论】:

    • 谢谢!这就像一个魅力!数据每年仅更新一次,因此非常有效!谢谢!
    【解决方案2】:

    您可以通过创建一个数组然后取消嵌套数组来进行一次扫描:

    select t.item, t.country, t.category, r.year, r.value
    from t cross join
         unnest( array[ cast(row(2017, t."2017") as row(year int, value int)),
                        cast(row(2018, t."2018") as row(year int, value int)),
                        cast(row(2019, t."2019") as row(year int, value int)),
                        cast(row(2020, t."2020") as row(year int, value int))
                      ]
               ) u(r);
    

    如果您的表确实是视图或复杂查询,则性能提升可能非常显着。

    【讨论】:

    • 感谢您对此进行调查。我试过了,但出现以下错误:SYNTAX_ERROR: line 3:21: Unknown type: row(year,value)
    • @dribble 。 . .我认为它需要类型。
    猜你喜欢
    • 2018-06-09
    • 1970-01-01
    • 2021-02-18
    • 2021-09-17
    • 1970-01-01
    • 2021-11-13
    • 1970-01-01
    • 2023-03-27
    • 2021-02-28
    相关资源
    最近更新 更多