挑战SQL查询以执行矩阵乘法

时间:2012-06-03 07:53:54

标签: mysql join currency

我有以下两个表:

sales
- id
- sales_price
- currency
- date

exchange
- currency
- conversion_to_usd
- date

在销售表中,我可以使用任意数量的货币,例如audchfnzd等...

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

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种货币。

1 个答案:

答案 0 :(得分: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;