我正在使用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
答案 0 :(得分:0)
您应该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