多列的不同值作为一个

Distinct value for multiplie column as one

我有一个 table transactions 列:id_transactioncredited_persondebited_person 和一个 table users id_user。 对于每个用户,我想要一个与他进行交易的所有人的列表(用户是借记还是贷记并不重要)

有人可以帮我吗?

您可以加​​入 userstransactions,按用户分组并使用 string_agg():

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