条件SUM不允许操作数

时间:2015-08-18 05:50:29

标签: sql sql-server aggregate-functions

我正在尝试将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这样的话,我怎样才能使它工作?

3 个答案:

答案 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