繁体   English   中英

一列中的 STRING_AGG() 和旁边列中的不同值

[英]STRING_AGG() in one column and distinct values in column next to

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

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]。

order by

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM