在case语句查询中增加临时变量值

时间:2015-03-06 06:05:43

标签: php mysql yii

使用case语句根据coloumn值计算计数,我使用以下代码执行此操作:

SET @tempVariable1 := 0;
SET @tempVariable2 := 0;
SELECT EMPLOYEEID,count(ADNUMBER),
                        CASE
                            WHEN AEERROR <> '--' then @tempVariable1:=@tempVariable1+1
                        ELSE 0
                        END AS Ext_err,
                        CASE
                            WHEN INTERNALERRORS <> '--' then @tempVariable2:=@tempVariable2+1
                        ELSE 0
                        END AS Int_err
FROM employee_productivity_details group by(EMPLOYEEID) LIMIT 2,20;

当我在工作台上运行时,它工作正常但是当我在PHP变量$sql中设置此查询时,它会显示错误。那么如何在查询中设置temperory变量?还有其他办法吗?

2 个答案:

答案 0 :(得分:1)

这样做你想要的吗?

SELECT EMPLOYEEID, count(ADNUMBER),
       SUM(AEERROR <> '--') AS Ext_err,
       SUM(INTERNALERRORS <> '--' ) AS Int_err
FROM employee_productivity_details
group by(EMPLOYEEID)
LIMIT 2, 20;

答案 1 :(得分:0)

根据需要,这对我来说很好。

 SELECT EMPLOYEEID,
     count(ADNUMBER),
     COALESCE(SUM(CASE INTERNALERRORS WHEN INTERNALERRORS <> '--' 
     THEN 0 ELSE 1 END), 0) as IntErr,
     COALESCE(SUM(CASE AEERROR WHEN AEERROR <> '--' 
     THEN 0 ELSE 1 END), 0) AS ExtErr 
   FROM employee_productivity_details 
   group by(EMPLOYEEID) order by EMPLOYEEID LIMIT 2,20;