在存储过程中使用SUM()中的CASE语句

时间:2013-02-13 11:32:46

标签: mysql stored-procedures mysqli

这是我的代码:

BEGIN

    SELECT SUM(
       CASE WHEN first_name > '' THEN 1 ELSE 0 END AS a 
       CASE WHEN last_name > '' THEN 1 ELSE 0 END AS b,             
       CASE WHEN country > '' THEN 1 ELSE 0 END AS c, 
       CASE WHEN state > '' THEN 1 ELSE 0 END AS d, 
       CASE WHEN city > '' THEN 1 ELSE 0 END AS e)
    AS total
    FROM employee_profile     
    WHERE id = user_id_in;

END

这会产生以下错误:

  

您的SQL语法中有错误,请检查与您的MySQL服务器版本对应的手册,以便在第一行的xxx错误附近使用正确的语法。

有人可以为此提供正确的语法帮助吗?

MySQL服务器版本:5.5.8

2 个答案:

答案 0 :(得分:2)

SUM采用单个参数(/列),它对多行进行求和,而不是单行的多个参数(/列),这就是它无效的原因。

这应该有效:

SELECT (CASE WHEN first_name > '' THEN 1 ELSE 0 END +
        CASE WHEN last_name  > '' THEN 1 ELSE 0 END +
        CASE WHEN country    > '' THEN 1 ELSE 0 END +
        CASE WHEN state      > '' THEN 1 ELSE 0 END +
        CASE WHEN city       > '' THEN 1 ELSE 0 END) AS total
FROM employee_profile     
WHERE id = user_id_in;

答案 1 :(得分:0)

尝试这个查询,这会很好地帮助你..

SELECT SUM(
    CASE 
    WHEN first_name  = ''  THEN '1'
    WHEN last_name  = ''  THEN '1'
    WHEN country  = '' THEN '1'
    WHEN state  = '' THEN '1'
    ELSE '0'
  END) AS total
FROM employee_profile     
    WHERE id = user_id_in;