简体   繁体   中英

How do I create a new column that holds all the primary key values of all rows that have the same value?

I read through multiple Questions here, but did not find the answer suiting my problem.

My table holds the following columns:

id |  name    |  fav_team
 1    John       Seahawks
 2    Patrick    Bengals
 3    Tom        Seahawks
 4    Kate       Seahawks

So I already figured out how to ask for all ids whose fav_team is 'Seahawks' but how do I manage to create a new column that for id 1 holds all the ids of that rows that have 'Seahawks' as fav_team as well, so that my output will look like this:

id    |   same_team
 1        3, 4
 3        1, 4
 4        1, 3

use group_concat()

    select group_concat(id) from table t1
     where exists ( select 1 from table t2 where t1.fav_team=t2.fav_team
                  ) and 

You can us a correlated subquery:

select t.*,
       (select group_concat(id order by id)
        from t t2
        where t2.fav_team = t.fav_team and t2.id <> t.id
       ) as others_with_same_favorite
from t;

You can also do this with window functions, but it requires diving into JSON and doing a lot of string manipulation:

select id,
       trim(',' from
            replace(regexp_replace(json_unquote(json_arrayagg(id) over (partition by fav_team)), '\\[|\\]|, ', ','),
                    concat(',', id, ','), ','
                   )
           )
from t
order by id;

Here is a db<>fiddle for this version.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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