转换为货币的多张发票金额之和
Sum of multiple invoices amount converted to a currency
我将 PostgreSQL 与 table 架构一起使用,该架构允许使用不同货币(例如欧元或美元)进行支付。我还有一个 table,其中包含每种货币对美元的兑换率。
我想对按 month/year 分组转换为美元的每笔付款金额求和。推荐的方法是什么?
我的 table 是:
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
您应该 join
查找 table 以获得美元以外货币的兑换率。
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
我将 PostgreSQL 与 table 架构一起使用,该架构允许使用不同货币(例如欧元或美元)进行支付。我还有一个 table,其中包含每种货币对美元的兑换率。
我想对按 month/year 分组转换为美元的每笔付款金额求和。推荐的方法是什么?
我的 table 是:
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
您应该 join
查找 table 以获得美元以外货币的兑换率。
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