4

我有一本货币兑换字典,如下:

exchange_rates = {'USD': 1.00000,
                  'EUR': 1.32875,
                  'GBP': 1.56718, ...}

然后我检索产品的销售信息,使用:

SELECT price, currency FROM sales

可能有一百万行,可能如下所示:

- 2.99    USD
- 3.01    EUR
- etc.

我将如何进行矩阵乘法以获得美元的总和?

4

3 回答 3

5

与其从数据库中获取一百万行并在 Python 中进行计算,不如将您的字典提供给数据库并让数据库进行计算并将结果发回给您。

您可以通过进行类似于以下的查询来做到这一点:

SELECT SUM(price * exchange_rate) AS total
FROM sales
LEFT JOIN
(
    SELECT 'USD' AS currency, 1.00000 AS exchange_rate
    UNION ALL
    SELECT 'EUR', 1.32875
    UNION ALL
    SELECT 'GBP', 1.56718
    -- ...
) AS exchange
ON exchange.currency = sales.currency
于 2012-05-08T22:46:58.793 回答
0

SELECT price FROM sales

然后总结你得到的所有项目,假设你表中的数字是美元。

于 2012-05-08T22:44:29.940 回答
0
SELECT SUM(price * factor) 
FROM 
       ( 
        SELECT sales.price AS price, exchange.factor AS factor
        FROM   sales
        JOIN   exchange ON exchange.currency = sales.currency
       ) AS t

这假设您有一个交换表

于 2012-05-08T22:53:27.223 回答