MYSQL:总和问题

时间:2013-06-17 07:12:44

标签: php mysql select sum

我遇到一个小问题,我的生活在顶部计算错误,但在获取数据的底部它们都是正确的。

它们存储在DB中,如下所示

生命= 1 IPP = 1 葬礼= 1

查询应该检查该行是否与1匹配并计算它。

 mysql_query("SELECT DISTINCT consultant, COUNT(*) as total, 
        sum(CASE WHEN life = '1' then 1 else 0 end) life,
        sum(CASE WHEN funeral = '1' then 1 else 0 end) funeral,
        sum(CASE WHEN IPP = '1' then 1 else 0 end) IPP
         FROM new WHERE call_date = '".$date."' and `qc_status` != 'Fail' GROUP BY consultant ORDER BY total DESC, life DESC, funeral DESC");

我有一个生命总数为9的工作人员但是当我在上面运行脚本时= 8

当我进一步查看列表时,我在4上有一名工作人员,在DB中有4名。

Full script.
{
        $totallife=0;
        $totalfuneral;
        $totalIPP;
        $total =0;
        $agents = mysql_query("SELECT DISTINCT consultant, COUNT(*) as total, 
        sum(CASE WHEN life = '' then 0 else 1 end) as life,
        sum(CASE WHEN funeral = '1' then 1 else 0 end) as funeral,
        sum(CASE WHEN IPP = '1' then 1 else 0 end) IPP
         FROM new WHERE call_date = '".$date."' and `qc_status` != 'Fail' GROUP BY consultant ORDER BY total DESC, life DESC, funeral DESC");
        while($agent = mysql_fetch_array($agents)){
            $totallife = $totallife+$agent[life];
            $totalfuneral = $totalfuneral+$agent[funeral];
            $totalIPP = $totalIPP+$agent[IPP];
            $total= $total+$agent[total];
            echo "<tr><td>".$agent[consultant]."</td><td>".$agent[life]."</td><td>".$agent[funeral]."</td><td>".$agent[IPP]."</td><td>".$agent[total]."</td></tr>";
        }

        echo "<tr><td><b>TOTALS</b></td><td><b>".$totallife."</b></td><td><b>".$totalfuneral."</b></td><td><b>".$totalIPP."</b></td><td><b>".$total."</b></td></tr>";
    }

1 个答案:

答案 0 :(得分:1)

DISTINCT移除SELECT,因为您已按该字段consultant进行分组:

SELECT 
    consultant, 
    COUNT(*) as total, 
    sum(CASE WHEN life = '1' then 1 else 0 end) life,
    sum(CASE WHEN funeral = '1' then 1 else 0 end) funeral,
    sum(CASE WHEN IPP = '1' then 1 else 0 end) IPP
FROM 
    new 
WHERE 
    call_date = '".$date."' 
    and `qc_status` != 'Fail' 
GROUP BY 
    consultant 
ORDER BY 
    total DESC, 
    life DESC, 
    funeral DESC