在MySQL中的Case语句中使用Sum

在MySQL中的Case语句中使用Sum,mysql,sum,case,Mysql,Sum,Case,我在MySQL中添加三个值时遇到问题,这应该很简单,对吗 我有基于第二列的值从列中选择值的代码,我使用如下case语句: Select Max(Case When Table1.costcode Like '%Costcode1%' Then Table1.costs Else Null End) As 'Costcode1', Max(Case When Tabl

我在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,但是Total Cost Case只返回Null

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

对这些值求和一定很简单,但显然我遗漏了一些东西…请帮助:-

谢谢

试试这个-

    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'

删除Total Cost后面的多余逗号。很抱歉,这是一个输入错误-实际sql会在这之后选择其他内容。请确认,Table1.costs列的数据类型为Decimal10,2。你能试试这个吗?尝试过这个选项,但仍然只得到0.00分。我很害怕。你是个明星!非常感谢,伙计,谢谢。经过三次尝试,我们终于成功了-