首页 > 解决方案 > 将列乘以一的不同值

问题描述

我有一个transactions带有 : id_transactioncredited_person和列debited_person的表和一个users带有id_user. 对于每个用户,我想要一个与他进行交易的所有人的列表(无论用户是借记还是贷记)

想要的结果

有人能帮助我吗 ?

标签: postgresqlgroup-bydistinct

解决方案


您可以加入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

推荐阅读