我有以下数据:
player_id level talent_id
1 1 a
1 2 b
1 3 c
2 1 d
2 2 e
并想按player_id分组并以行作为结构,以level
值作为结构字段名称:
player_id data
1 {_1 = a, _2 = b, _3 = c}
2 {_1 = d, _2 = e, _3 = null}
级别列始终来自{1、2、3}的集合,但是某些级别可能会丢失(空)
到目前为止,我所获得的是根据player_id进行聚合并附带结果数组:
talents as (
select
p.player_id,
array_agg(struct(p.level, p.talent_id)) as talents
from source.player_talent p
group by player_id
),
player_id data
1 [{1, a}, {2, b}, {3, c}]
2 {{1, d}, {2, e}]
现在我需要将此数组映射到具有固定属性名称_1
,_2
,_3
的结构
答案 0 :(得分:3)
这将返回预期结果:
WITH Players AS (
SELECT 1 AS player_id, 1 AS level, 'a' AS talent_id UNION ALL
SELECT 1, 2, 'b' UNION ALL
SELECT 1, 3, 'c' UNION ALL
SELECT 2, 1, 'd' UNION ALL
SELECT 2, 2, 'e'
)
SELECT
player_id,
STRUCT(
MAX(IF(level = 1, talent_id, NULL)) AS _1,
MAX(IF(level = 2, talent_id, NULL)) AS _2,
MAX(IF(level = 3, talent_id, NULL)) AS _3) AS data
FROM Players
GROUP BY player_id
这里的技术称为透视(将行转换为列)。