BigQuery GROUP_CONCAT and ORDER BY

前端 未结 3 1940
被撕碎了的回忆
被撕碎了的回忆 2020-12-10 19:14

I am currently using BigQuery and GROUP_CONCAT which works perfectly fine. However, when I try to add a ORDER BY clause to the GROUP_CONCAT statement like I would do in SQL,

3条回答
  •  庸人自扰
    2020-12-10 19:28

    Here is a version in Standard SQL mode in BigQuery with ARRAY_AGG as aggregate function:

    select key,
    array_agg(struct(grouped_value) order by array_length(grouped_value) desc limit 1)[offset(0)].*
    from (
    select 
      key, 
      array_agg(value) over 
        (partition by key
         order by value asc
         rows between unbounded preceding and unbounded following) 
      grouped_value 
    from (
    select key, value from unnest([
        struct(1 as key, "b" as value)
      , struct(1, "c")
      , struct(1, "a")
      , struct(2, "y")
      , struct(2, "x")
    ]))) group by key
    

提交回复
热议问题