如何以正确的方式对阵列进行分组

时间:2019-05-15 14:44:41

标签: google-bigquery

我需要从下表中每participant_name获得race_name名获奖者

WITH race AS (    
  SELECT 'A' AS race_name, [4, 1, 3] as participant_id, [25.3, 29.4, 24.1] as timing  UNION ALL    
  SELECT 'B', [2, 1, 4, 6], [16.3, 14.2, 17.4, 18.3] UNION ALL    
  SELECT 'C', [7, 5, 4, 2], [19.5, 21.4, 16.4, 15.6]     
),

participant AS (    
  SELECT 1 as participant_id, 12 as participant_age, "Julie" as participant_name UNION ALL    
  SELECT 2, 11, "Max" UNION ALL    
  SELECT 3, 12, "John" UNION ALL    
  SELECT 4, 11, "Matt" UNION ALL    
  SELECT 5, 13, "Diana" UNION ALL    
  SELECT 6, 12, "Peter" UNION ALL    
  SELECT 7, 11, "Ben"     
)

SELECT race_name, 
  (SELECT participant_name 
    FROM participant CROSS JOIN UNNEST(timing) AS duration 
    ORDER BY duration ASC 
    LIMIT 1
  )
FROM race 

我收到participant_name个参与者的时间最短,但不是每个race_name。如何解决?

1 个答案:

答案 0 :(得分:2)

以下是用于BigQuery标准SQL

#standardSQL
SELECT race_name, 
  (SELECT participant_name
    FROM UNNEST(participant_id) AS participant_id WITH OFFSET 
    JOIN UNNEST(timing) AS duration WITH OFFSET USING(OFFSET)
    LEFT JOIN participant USING(participant_id)
    ORDER BY duration ASC 
    LIMIT 1
  ) participant_name 
FROM race

如果要应用于您的问题的样本数据-结果为

Row race_name   participant_name     
1   A           John     
2   B           Julie    
3   C           Max