【问题标题】:Dynamic Column Alias Creation & Joining动态列别名创建和加入
【发布时间】:2020-03-11 22:55:03
【问题描述】:

我正在尝试在雪花中查询一些数据并为自己节省一堆硬编码

我的数据行(我们称之为子查询A)看起来像这样

| my_index  | score | some_enum |
|-----------|-------|-----------|
| abc.      | 100.  | x.        |
| abc.      | 50.   | x.        |
| abc.      | 50.   | y.        |
| abc.      | 60.   | y.        |
| def.      | 90.   | z.        |

我想按my_indextest_name 分组,计算平均分数,然后将所有这些数据与基于some_enum 的动态列名重新连接在一起,所以它看起来像

| my_index  | avg_score_x | avg_score_y | avg_score_z | avg_score |
|-----------|-------------|-------------|-------------|-----------|
| abc.      | 75.         | 55.         | 0/NaN/-1.   | 65.       |
| def.      | 0/NaN/-1.   | 0/NaN/-1.   | 90.         | 90.       |

有没有人有一种简洁的方法来动态创建这些列名并加入这些数据?

【问题讨论】:

    标签: sql group-by pivot snowflake-cloud-data-platform


    【解决方案1】:

    你可以做条件聚合:

    select
        myindex,
        avg(case when some_enum = 'x' then score end) avg_score_x,
        avg(case when some_enum = 'y' then score end) avg_score_y,
        avg(case when some_enum = 'z' then score end) avg_score_z,
        avg(score) avg_score
    from a
    group by myindex
    order by myindex
    

    【讨论】:

    • 谢谢,这会很有帮助——不过我有很多专栏(想象一下 avg_scorescore_variancemedian_score 等),所以虽然我绝对可以把它全部写出来枚举,会有点乱。有没有办法将所有内容重新连接在一起,但使用基于 some_enum 值的动态列名?
    • @mjkaufer:这需要动态SQL,即构建一个查询字符串,然后执行它。这真是另一种野兽。
    • 还有一个内置的 PIVOT。但它也需要动态sql。
    猜你喜欢
    • 2021-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-06
    • 2018-04-07
    相关资源
    最近更新 更多