2015-12-15 24 views
0

我使用的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

您是否有USD-> USD = 1的記錄?您是否可以依靠在兌換表中使用的每種貨幣都有條目,或者您是否應該檢查並在缺勤情況下采取措施? –

+0

我相信我們會有美元 - >美元= 1.0,但我認爲最好有一個查詢準備處理該失蹤記錄! – h3ct0r

回答

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