gpt4 book ai didi

postgresql,将列转换为没有rowid的标题

转载 作者:行者123 更新时间:2023-11-29 13:43:56 26 4
gpt4 key购买 nike

我正在尝试将一列查询到标题中并对其求和。
我看到了一些使用交叉表的示例,但我不知道如何在没有 rowid 的情况下使其工作

是否有其他解决方法可以使其正常工作?

我的 table

货币|金额
人民币 | 12
IDR | 30
人民币 | 22
美元 | 58
IDR | 30

预期查询

RMB_sum | IDR_sum | USD_sum
34 | 60 | 58

最佳答案

正如您所说,您在编写此查询时预先知道所有货币值,您可以简单地使用条件聚合。当您使用 PostgreSQL 9.1 时,您只能通过将 sum() 与 case 语句混合来实现此目的:

select
sum(case when currency = 'RMB' then amount else 0 end) as RMB_sum,
sum(case when currency = 'IDR' then amount else 0 end) as IDR_sum,
sum(case when currency = 'USD' then amount else 0 end) as USD_sum
from
__transactions

(请注意,上面使用了隐式分组——我的 select 语句中的所有内容都是一个聚合函数,因此不需要显式地对查询进行分组)


如果您使用的是 PostgreSQL 9.4+,则可以使用 filter 指令简化上述内容:

select
sum(amount) filter(where currency = 'RMB') as RMB_sum,
sum(amount) filter(where currency = 'IDR') as IDR_sum,
sum(amount) filter(where currency = 'USD') as USD_sum
from
__transactions

关于postgresql,将列转换为没有rowid的标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51420074/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com