MySQL查询中的多个嵌套if语句

时间:2012-02-23 23:08:18

标签: mysql

我正在尝试下面的查询,MySQL给了我这个错误:组功能的使用无效

 SELECT C.`some_name`,
        SUM(IF(A.`med_type` = 1, SUM(A.`med_qty`), 0)) AS total,
        SUM(IF(A.`is_rejected` = 4, 1 , 0)) AS approved, 
        SUM(IF(A.`is_rejected` = 2, 1 , 0)) AS qeue, 
        SUM(IF(A.`is_rejected` = 3, 1 , 0)) AS rejected, 
        SUM(IF(A.`is_rejected` = 1, 1 , 0)) AS fresh
   FROM `ne_media` A
  INNER JOIN `ne_member` B ON A.`mem_id`  = B.`mem_id`
  INNER JOIN `ne_some`   C ON B.`some_id` = C.`some_id`
  GROUP BY C.`some_id`;

我想将med_qty归结为med_type = 1

我该怎么办?

1 个答案:

答案 0 :(得分:1)

使用:

    SUM(CASE WHEN (A.`med_type` = 1) THEN A.`med_qty` ELSE 0 END)) AS total,

或:

    SUM(IF(A.`med_type` = 1, A.`med_qty`, 0)) AS total,

您不能像在原版中尝试的那样对聚合进行聚合。