Postgresql 多行列的不同值为一

Postgresql 多行列的不同值为一,postgresql,group-by,distinct,Postgresql,Group By,Distinct,我有一个带有列的表事务:id\u transaction、credited\u person、debited\u person和一个带有id\u user的表用户。 对于每个用户,我想要一份他与之进行交易的所有人的列表,不管用户是借记还是贷记 有人能帮我吗?您可以将用户加入到交易中,按用户分组并使用: 有没有一种方法可以让count of person代替list?@J.doe代替string\u agg use count*或countdistinct case…end。 select u.u

我有一个带有列的表事务:id\u transaction、credited\u person、debited\u person和一个带有id\u user的表用户。 对于每个用户,我想要一份他与之进行交易的所有人的列表,不管用户是借记还是贷记

有人能帮我吗?

您可以将用户加入到交易中,按用户分组并使用:


有没有一种方法可以让count of person代替list?@J.doe代替string\u agg use count*或countdistinct case…end。
select u.user_id,
  string_agg(distinct
    case 
      when u.user_id = t.credited_person then t.debited_person
      else t.credited_person
    end,
    ','
  )
from users u left join transactions t
on u.user_id in (t.credited_person, t.debited_person)
group by u.user_id