带有COUNT或SUM问题的SQL CASE

时间:2015-09-15 10:13:51

标签: mysql count sum case

我尝试了一些选项,但它根本不起作用或不符合我的需要。

关于以下SQL(这不起作用,但最接近我需要的):

SELECT CASE WHEN r.`content` LIKE '% word1 %' 
            then 1 
            else 0 
      END AS `val1`
    , CASE WHEN r.`content` LIKE '% word2 %' 
           then 1 
           else 0 
      END AS `val2`
    , CASE WHEN r.`city` LIKE 'cityname' 
           then 1 
           else 0 
      END AS `val3`
    , (`val1`+`val2`+`val3`) AS `reference_value` 
FROM `testimonials` as r 
WHERE `accepted`='1' 
ORDER BY `reference_value`

所以基本上,积分最多的条目最终排在最前面。当3个案例匹配reference_value时将有3个点。 代码是动态的,因此它也可以是4,5,6,7或更多CASE。

我希望这对你有意义。 提前谢谢。

2 个答案:

答案 0 :(得分:3)

您无法在同一val1列表中重复使用计算值(例如查询中的SELECT)。

使用子查询,或重复CASE以对其值求和。在这种情况下,我的偏好是子查询,但实际要求和实际执行计划(解释)可以随时覆盖它。

SELECT
  val1,val2,val3,
  val1+val2+val3 as reference_value
FROM (
  SELECT CASE WHEN r.`content` LIKE '% word1 %' 
            then 1 
            else 0 
      END AS `val1`
    , CASE WHEN r.`content` LIKE '% word2 %' 
           then 1 
           else 0 
      END AS `val2`
    , CASE WHEN r.`city` LIKE 'cityname' 
           then 1 
           else 0 
      END AS `val3`
  FROM `testimonials` as r 
  WHERE `accepted`='1' 
) TMP
ORDER BY `reference_value`

答案 1 :(得分:0)

SELECT *,val1+val2+val3 AS `reference_value` FROM (
    CASE WHEN r.content LIKE '% word1 %' 
        then 1 
        else 0 
    END AS `val1`
   ,CASE WHEN r.content LIKE '% word2 %' 
       then 1 
       else 0 
   END AS `val2`
  ,CASE WHEN r.city LIKE 'cityname' 
       then 1 
       else 0 
  END AS `val3`
  ,  
  FROM `testimonials` as r 
  WHERE `accepted`='1' 
)
ORDER BY `reference_value`