MySQL有条件地计算结果

时间:2011-10-31 21:54:22

标签: mysql sum

我有一个查询,它返回几种不同类型记录的计数,但我现在需要进一步限定结果集。我很好奇是否有一种优雅的方式将这些语句组合成一个语句。基本上,如果第2列为true,则增加ND_true,如果第2列为false,则增加ND_false。

sum(if(c.1 = 'ND' and c.2 is true, if(c.2 = 'P', 1, 0), 0)) as 'ND_true'
sum(if(c.1 = 'ND' and c.2 is false, if(c.2 = 'P', 1, 0), 0)) as 'ND_false'

3 个答案:

答案 0 :(得分:0)

企业风险管理...

select count(*) from `tablename` where [something something something]

似乎是一个比你正在做的更好的替代方案。要么你或者你没有非常清楚地解释你在做什么以及是什么导致你得到了解决方案。

答案 1 :(得分:0)

另一种选择:

Select ...
    , C.ND_True As ND_True
    , C.ND_False As ND_False
From ...
    Cross Join  (
                Select Sum( Case When C1.P = 1 Then 1 Else 0 End ) As ND_True
                    , Sum( Case When C1.P = 0 Then 1 Else 0 End ) As ND_False
                From SomeTable As C1
                Where C1.1 = 'ND'
                    And C1.P = 'P'
                Union All
                Select Z.Val, Z.Val
                From ( Select 0 As Val ) As Z
                Where Not Exists    (
                                    Select 1
                                    From SomeTable As C2
                                    Where C2.1 = 'ND'
                                        And C2.P = 'P'
                                    )
                ) As C

答案 2 :(得分:0)

您的查询示例虽然简短但不清楚...您首先测试c1 ='ND'(字符串比较)与c.2进行对比(暗示c.2是合乎逻辑的),然后是另一个if(c.2 =' P'...)我确定你缩写列名,但这没有意义。 c.2是逻辑字段还是字符串字段......一个或另一个。

sum(if(c.1 = 'ND' and c.2 is true, if(c.2 = 'P', 1, 0), 0)) as 'ND_true'
sum(if(c.1 = 'ND' and c.2 is false, if(c.2 = 'P', 1, 0), 0)) as 'ND_false'

以下是我认为您正在寻找的简化版本。在这种情况下,您关注c.1是“ND”,因此将其作为WHERE子句来限制从表中检索的内容。然后,您不必将其作为IF()子句测试的一部分重新复制。然后,只需输入“其他”标准,其中我有c.2表达式......由于该子句对于正在测试的内容是相同的,因此第2和第3列会触发它们将被计入的列...

select
      sum( if( c.2, 1, 0 )) as ND_True,
      sum( if( c.2, 0, 1 )) as ND_False
   from
      yourTable c
   where
      c.1 = 'ND'

例如:数据

col1     col2
AX       true
BC       true
ND       true     <-- this row
XY       false
ND       true     <-- this row
ND       false    <-- this row
AX       false
ND       true     <-- this row

将导致仅查询4个标记的行,最终计数为

ND_True = 3
ND_False = 1