【问题标题】:STRING_AGG() in one column and distinct values in column next to一列中的 STRING_AGG() 和旁边列中的不同值
【发布时间】:2020-11-09 00:20:17
【问题描述】:

我目前正在使用这样的查询来聚合字符串:

select
  STRING_AGG(pet_name) over (partition by id, name, second_id, second_name ORDER BY pet_id) pet_names
  id, 
  name, 
  second_id, 
  second_name
 FROM `example`
|---------------------|--------|------------------|------------------|------------------|
|      pet_names      |   id   |        name      |     second_id    |   second_name    |
|---------------------|--------|------------------|------------------|------------------|
|   [cat, dog, bird]  |    1   |       anna       |          2       |       rose       |    
|---------------------|--------|------------------|------------------|------------------|
|  [cat, bear, tiger] |    2   |       kate       |          3       |       mike       |  
|---------------------|--------|------------------|------------------|------------------|
|    [cat, tiger]     |    3   |       john       |          2       |       bate       | 
|---------------------|--------|------------------|------------------|------------------|

但是,我想最终得到这样的表(这里是上表第一行的示例):

|---------------------|--------|------------------|------------------|------------------|--------|
|      pet_names      |   id   |        name      |     second_id    |   second_name    |pet_name|
|---------------------|--------|------------------|------------------|------------------|--------|
|   [cat, dog, bird]  |    1   |       anna       |          2       |       rose       |   cat  |
|---------------------|--------|------------------|------------------|------------------|--------|
|   [cat, dog, bird]  |    1   |       anna       |          2       |       rose       |   dog  | 
|---------------------|--------|------------------|------------------|------------------|--------|
|   [cat, dog, bird]  |    1   |       anna       |          2       |       rose       |   bird |
|---------------------|--------|------------------|------------------|------------------|--------|

当我尝试时:

select
  STRING_AGG(pet_name) over (partition by id, name, second_id, second_name ORDER BY pet_id) pet_names
  id, 
  name, 
  second_id, 
  second_name,
  pet_name
 FROM `example`

对于pet_name "cat" 返回 [cat],然后为 pet_name "dog" 等返回 [cat, dog] 并不能正常工作。

【问题讨论】:

  • 你的输入数据是什么?
  • 正如@MikhailBerlyant 所说,请提供一些输入数据。它可以帮助我们重现问题

标签: sql arrays string google-bigquery


【解决方案1】:

删除order by:

select string_agg(pet_name) over (partition by id, name, second_id, second_name) as pet_names,
       . . . 
from `example`

order by 使窗口函数在partition by 键定义的每个组内“累积”。如果没有order by,则为具有相同partition by 键的所有行返回一个值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-09
    • 2018-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多