【问题标题】:Using Sum inside a Case statement in MySQL在 MySQL 的 Case 语句中使用 Sum
【发布时间】:2012-05-25 10:17:28
【问题描述】:

我在 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 列还包含许多其他代码,所以我不能在不先将它们挑出的情况下将所有值相加。

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

谢谢

【问题讨论】:

  • 去掉总成本后多余的逗号。
  • 抱歉打错了 - 实际的 sql 在此之后选择其他内容。

标签: mysql sum case


【解决方案1】:

试试这个 -

    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'

【讨论】:

  • 确认一下,Table1.costs 列的数据类型为 Decimal(10,2)
  • 已编辑。你可以试试这个吗?
  • 试过这个选项,但仍然只得到 0.00 我很害怕。
  • 你是明星!谢谢一百万老兄。
  • 谢谢。经过3次尝试,我们终于得到了它。 :-)
猜你喜欢
  • 2017-05-11
  • 1970-01-01
  • 2012-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多