在MySQL中的Case语句中使用Sum

时间:2012-05-25 10:17:28

标签: mysql sum case

我在MySQL中添加三个值有问题,这应该很简单吗?

我有代码根据第二列的值从列中选择值,我使用这样的case语句:

Select
        Max(Case
            When Table1.costcode Like '%Costcode1%' 
            Then Table1.costs 
            Else Null End) As 'Costcode1',
        Max(Case
            When Table1.costcode Like '%Costcode2%' 
            Then Table1.costs
            Else Null End) As 'Costcode2',
        Max(Case
            When Table1.costcode Like '%Costcode3%' 
            Then Table1.costs 
            Else Null End) As 'Costcode3',
        (Case
            When Table1.costcode In ('%Costcode1%','%Costcode2%','%Costcode3%')
            Then Sum(Table1.costs)
            Else Null End) As 'Total Cost',

From Table1

前三个Case语句工作正常且所有返回值(这些都作为负数保存在数据库中,例如-13624.00),但总成本案例只返回Null ...

列Table1.costcode还包含许多其他代码,所以我不能在不先取出它们的情况下对所有值求和。

总结这些值必须简单,但显然我遗漏了一些东西......请帮助: - )

由于

1 个答案:

答案 0 :(得分:0)

试试这个 -

    SUM(Case Table1.costcode
        When LIKE ('%Costcode1%') Then Table1.costs
        When LIKE ('%Costcode2%') Then Table1.costs
        When LIKE ('%Costcode3%') Then Table1.costs
        Then Table1.costs
        Else 0.00 End) As 'Total Cost'