【发布时间】:2020-04-03 23:13:36
【问题描述】:
我有一个表 transactions 与列:id_transaction、credited_person、debited_person 和一个表 users 和 id_user。
对于每个用户,我想要一个与他进行交易的所有人的列表(无论用户是借记还是贷记)
有人可以帮帮我吗?
【问题讨论】:
标签: postgresql group-by distinct
我有一个表 transactions 与列:id_transaction、credited_person、debited_person 和一个表 users 和 id_user。
对于每个用户,我想要一个与他进行交易的所有人的列表(无论用户是借记还是贷记)
有人可以帮帮我吗?
【问题讨论】:
标签: postgresql group-by distinct
你可以加入users到transactions,按用户分组并使用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
【讨论】:
string_agg() 使用count(*) 或count(distinct case...end)。