Sql 多张发票金额之和转换为一种货币

Sql 多张发票金额之和转换为一种货币,sql,postgresql,sum,currency,Sql,Postgresql,Sum,Currency,我正在使用PostgreSQL和表模式,允许以欧元或美元等不同货币进行支付。我还有一张表,上面有每种货币对美元的兑换率 我想将每个月/年的付款金额换算成美元。推荐的方法是什么 我的桌子是: CREATE TABLE invoice ( invoice_id serial, ... amount numeric, currency_type_id text, created_date timestamp without time zone, ); CREATE TABLE c

我正在使用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

您应该
加入查找表,以获取美元以外货币的兑换率

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
选择提取(从创建日期算起的月份)作为周一,
提取(从创建日期算起的年份)为yyyy,
金额(如果c.code_从“USD”开始,然后是金额*c.rate else金额结束)作为“销售”
从发票一
加入i.currency\u type\u id=c.code\u from上的汇率c
其中c.code_to=‘USD’
按1,2分组
按2,1的顺序排列

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