动态列别名创建和加入



我试图在snowflake中查询一些数据,并为自己保存一堆硬编码

我的数据行(让我们把这个子查询称为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.       |

有人有一种干净的方法来动态创建这些列名并连接这些数据吗?

您可以进行条件聚合:

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

最新更新