2

我有以下两个表:

sales
- id
- sales_price
- currency
- date

exchange
- currency
- conversion_to_usd
- date

在销售表中,我可能有任意数量的货币,例如aud, chf,nzd等...

我需要将总销售额转换为美元。以下将是一个手动示例:

sales
(10.20, 'NZD', '2012-10-01')
(4.15,  'AUD', '2012-09-01')
...

exchange
('AUD', 1.02, '2012-08-01')
('AUD', 1.03, '2012-09-01')
('NZD', 0.89, '2012-10-01)

  10.20 (cost NZD) * 0.89 (NZD conversion) 
+ 4.15 (cost AUD) * 1.03 (AUD conversion)
= 13.3525

我可以针对单个货币执行此操作,但是很难概括查询以获取给定日期的所有总和。

SELECT SUM(sales_price) * conversion_to_usd FROM sales
    INNER JOIN exchange
    using (currency, date) 
    WHERE currency = "AUD" and date = "2012-09-01"

给定一个日期,我将如何执行此组合查询?

我想得到以下形式的结果:

sales_in_usd    currency       date
100             AUD            2012-01-01
150             CAD            2012-01-01
40              DKK            2012-01-01
36              JPY            2012-01-01
etc...

请注意,我正在寻找一般查询,因为将有超过 30 种货币。

4

1 回答 1

1

你试过GROUP BY命令吗?

SELECT SUM(sales_price) * conversion_to_usd AS 'Sales in US$', 
    currency AS 'Currency', 
    date AS 'Date' FROM sales
INNER JOIN exchange
    USING (currency, date) 
WHERE date = "2012-09-01"
GROUP BY currency;
于 2012-06-03T07:58:31.760 回答