[英]Dynamic Column Alias Creation & Joining
I'm trying to query some data in snowflake and save myself a bunch of hard-coding我正在尝试在雪花中查询一些数据并为自己节省一堆硬编码
My data rows (let's call this subquery A
) look something like this我的数据行(我们称之为子查询A
)看起来像这样
| my_index | score | some_enum |
|-----------|-------|-----------|
| abc. | 100. | x. |
| abc. | 50. | x. |
| abc. | 50. | y. |
| abc. | 60. | y. |
| def. | 90. | z. |
I want to group by my_index
and test_name
, compute average scores, and then join all of this data back together with dynamic column names based on some_enum
, so it would look something like我想按my_index
和test_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. |
Does anybody have a clean way of dynamically creating these column names and joining this data?有没有人有一种干净的方法来动态创建这些列名并加入这些数据?
You can do conditional aggregation:您可以进行条件聚合:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.