【问题标题】:Sum of multiple invoices amount converted to a currency转换为货币的多张发票金额的总和
【发布时间】:2015-12-15 14:55:42
【问题描述】:

我正在使用带有表模式的 PostgreSQL,该表模式允许以不同货币(如欧元或美元)进行支付。我还有一张表,其中列出了每种货币对美元的兑换率。

我想计算按月/年分组的每笔转换为美元的付款金额的总和。推荐的方法是什么?

我的桌子是:

CREATE TABLE invoice
(
  invoice_id serial,
  ...
  amount numeric,
  currency_type_id text,
  created_date timestamp without time zone,
);

CREATE TABLE currency_rates
(
  code_from text,
  code_to text,
  rate numeric,
);

我的实际查询只是对按月份分组的值求和:

select extract(month from created_date) as mon, 
extract(year from created_date) as yyyy,
sum(amount) as "Sales" 
from invoice 
group by 1,2 
order by 2,1

【问题讨论】:

  • 请发表您的尝试
  • 你有USD->USD=1的记录吗?您是否可以依靠使用的每种货币在转换表中都有一个条目,或者您应该检查并在缺席的情况下做些什么?
  • 我相信我们将会有 USD->USD = 1.0,但我认为最好准备一个查询来处理那个缺失的记录!

标签: sql postgresql sum currency


【解决方案1】:

您应该join 查找表以获取美元以外货币的兑换率。

select extract(month from created_date) as mon, 
extract(year from created_date) as yyyy, 
sum(case when c.code_from <> 'USD' then amount * c.rate else amount end) as "Sales" 
from invoice i
join currency_rates c on i.currency_type_id = c.code_from
where c.code_to = 'USD'
group by 1,2 
order by 2,1

【讨论】:

    猜你喜欢
    • 2021-03-15
    • 2020-11-26
    • 2021-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-28
    • 1970-01-01
    相关资源
    最近更新 更多