【问题标题】:Distinct value for multiplie column as one多列的不同值作为一
【发布时间】:2020-04-03 23:13:36
【问题描述】:

我有一个表 transactions 与列:id_transactioncredited_persondebited_person 和一个表 usersid_user。 对于每个用户,我想要一个与他进行交易的所有人的列表(无论用户是借记还是贷记)

有人可以帮帮我吗?

【问题讨论】:

    标签: postgresql group-by distinct


    【解决方案1】:

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

    【讨论】:

    • 有没有办法统计人数而不是列表?
    • @J.doe 而不是string_agg() 使用count(*)count(distinct case...end)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-14
    • 1970-01-01
    相关资源
    最近更新 更多