【发布时间】:2020-12-05 17:49:49
【问题描述】:
我有以下可重现的示例,因为标题可能不是 100% 清楚,示例应该有所帮助:
with
player_heights as (
select 'joe' as name, 0.35 as height union all
select 'tom' as name, 0.75 as height union all
select 'nick' as name, 0.2 as height union all
select 'sal' as name, 1.2 as height union all
select 'chris' as name, 0.5 as height union all
select 'cob' as name, null as height union all
select 'jeff' as name, 1.1 as height union all
select 'pob' as name, 0.71 as height
),
players_table as (
select 'joe' as p1, 'tom' as p2, 'nick' as p3, 'sal' as p4, 'chris' as p5, 0.35 as h1, 0.75 as h2, 0.2 as h3, 1.2 as h4, 0.5 as h5 union all
select 'joe' as p1, 'nick' as p2, 'cob' as p3, 'jeff' as p4, 'pob' as p5, 0.35 as h1, 0.2 as h2, null as h3, 1.1 as h4, 0.71 as h5 union all
select 'tom' as p1, 'chris' as p2, 'sal' as p3, 'jeff' as p4, 'pob' as p5, 0.75 as h1, 0.5 as h2, 1.2 as h3, 1.1 as h4, 0.71 as h5
)
select
concat(p1, '-', p2, '-', p3, '-', p4, '-', p5) as players
,*
from players_table
每个人都与一个身高相关联,来自player_heights 表。在players_table 中,每行有 5 个人,每个人的身高都已连接到桌子上。
对于players_table 中的每一行,需要将 5 个玩家连接成一个字符串。挑战在于这些玩家应该根据他们的身高进行排序,从最小到最大,null height person 在连接字符串的末尾。目前,我正在使用的基本concat 中没有考虑高度。第二行中players 列的正确输出将是nick-joe-pob-jeff-cob。
编辑
我考虑过使用嵌套的 case when 语句,但是 5 个人有 120 种可能的玩家排序,这对于 case when 来说似乎太多了
编辑 2
如果这是不可能的,那么另一个可行的解决方案是在concat 之前按字母顺序对人员进行排序。这并不理想,但可能更简单。
更新
添加到最终选择 ARRAY(SELECT x FROM UNNEST(array<string>[p1, p2, p3, p4, p5]) AS x ORDER BY x) AS arr2 的以下列确实从 5 个字符串列创建了一个数组,然后对它们进行排序。所以这是朝着正确的方向发展,但我还没有办法在这里使用额外的高度值。
select
*
,array_to_string(
array(select x from unnest(array[p1, p2, p3, p4, p5]) as x order by x),
'-'
) as players
【问题讨论】:
标签: google-bigquery