【问题标题】:how to merge two rows in postgres using select [duplicate]如何使用select合并postgres中的两行[重复]
【发布时间】:2021-03-01 19:56:33
【问题描述】:

我有一个表格,其中的行看起来像这样

Account Currency Amount
1 USD 5
1 EUR 10
2 USD 8
3 EUR 4

有没有办法做一个选择查询,所以它会返回类似的东西

Account amount_usd amount_eur
1 5 10
2 8
3 4

usd 和 eur 是硬编码的,所以我不必从列中构建名称。

【问题讨论】:

标签: sql postgresql


【解决方案1】:

您可以使用 Postgres 中使用 filter 的条件聚合:

select account,
       sum(amount) filter (where currency = 'USD') as usd_amount,
       sum(amount) filter (where currency = 'EUR') as eur_amount
from t
group by account;

【讨论】:

    【解决方案2】:

    你可以在条件下使用 sum() :

    select account, sum(case when currency='USD' then amount end) Amount_USD,
    sum(case when currency='EUR' then amount end) Amount_EUR
    from myTable
    Group by account
    

    【讨论】:

      猜你喜欢
      • 2021-11-09
      • 1970-01-01
      • 2018-09-14
      • 2012-08-31
      • 2022-01-02
      • 2019-05-01
      • 2021-11-23
      • 1970-01-01
      相关资源
      最近更新 更多