我正在尝试将SUM
Order
amount
转换为固定货币。 amount
表中的Order
可以是不同的货币。
如果IsBase
表格中的Currency
标记为1
,那么我想与Rate
分开,否则我想与Rate
相乘
SELECT CASE WHEN c.isBase = 1
THEN SUM(o.Amount / c.Rate)
ELSE SUM(o.Amount * c.Rate)
END
FROM Orders o JOIN Currency c
ON o.Currency = c.Currency
这不起作用并给出错误:
列c.isBase'在选择列表中无效,因为它不是 包含在聚合函数或GROUP BY子句中。
但上述专栏不属于SELECT
。它是SELECT
中条件的一部分。如果我想要SUM
这样的话,我怎样才能使它工作?
答案 0 :(得分:3)
SELECT SUM(CASE WHEN c.isBase = 1
THEN o.Amount / c.Rate
ELSE o.Amount * c.Rate
END) AS answer
FROM Orders o JOIN Currency c
ON o.Currency = c.Currency
答案 1 :(得分:1)
您应该将CASE
表达式放在SUM
聚合函数中:
SELECT
SUM(CASE WHEN c.isBase = 1 THEN o.Amount / c.Rate ELSE o.Amount * c.Rate END)
FROM Orders o
JOIN Currency c
ON o.Currency = c.Currency
答案 2 :(得分:0)
请尝试以下
SELECT CASE WHEN c.isBase = 1
THEN SUM(o.Amount / c.Rate)
ELSE SUM(o.Amount * c.Rate)
END
FROM Orders o JOIN Currency c
ON o.Currency = c.Currency
GROUP BY c.isBase