如何使用SUMIF或任何SQL查询来汇总调查数据的结果或结果?

时间:2018-03-28 01:52:59

标签: php mysql sql laravel laravel-5.4

我在这里使用仪表板中的查询来对调查回复进行排序。我想要的是我的查询添加ff的结果即。

'Male - In Love' + 'Female - In Love'; 
'Male - Like' + 'Female - Like'; 
'Male - Facepalm' + 'Female - Facepalm'; 
'Male - Crying' + 'Female - Crying';

以下是我用于对个人回复进行排序的查询:

顺便说一句,我正在使用laravel 5.4和mysql

public function getDataTwo(Request $request){
    $data = DB::connection('mysql')->select(DB::raw("SELECT 
        DATE(`created_at`) as 'DATE',
        SUM(IF(`responses`=1,1,0)) as 'Male - In Love',
        SUM(IF(`responses`=2,1,0)) as 'Male - Like',
        SUM(IF(`responses`=3,1,0)) as 'Male - Facepalm',
        SUM(IF(`responses`=4,1,0)) as 'Male - Crying',
        SUM(IF(`responses`=5,1,0)) as 'Female - In Love',
        SUM(IF(`responses`=6,1,0)) as 'Female - Like',
        SUM(IF(`responses`=7,1,0)) as 'Female - Facepalm',
        SUM(IF(`responses`=8,1,0)) as 'Female - Crying'
        FROM `answers` 
        WHERE DATE(`created_at`) BETWEEN DATE('$request->startDate') AND
        DATE('$request->endDate')                             
        AND TIME(`created_at`) BETWEEN TIME('$request->startDate') AND 
        TIME('$request->endDate')
        -- AND driverid = ('*')
        -- AND busid = ('*')
        -- AND routeid = ('*')
        -- AND questionid = ('*') 
        GROUP BY DATE(`created_at`)"
    )); //Array and Result nito
    $tempArr = array();
    if(count($data)==0){return $data;}
    $xcnt=0;
    foreach ($data[0] as $key => $value) {
        if($key=='DATE'){continue;}
        $tempArr[$xcnt]=array("name"=>$key,"y"=>(int)$value);
        $xcnt++;
    }
    $data = json_encode($tempArr);
    return $data;
}

1 个答案:

答案 0 :(得分:0)

您正在使用MySQL,因此可以使用此快捷方式更轻松地编写查询:

SELECT DATE(created_at) as DATE,
       SUM(responses = 1) as `Male - In Love`,
       SUM(responses = 2) as `Male - Like`,
       SUM(responses = 3) as `Male - Facepalm`,
       SUM(responses = 4) as `Male - Crying`,
       SUM(responses = 5) as `Female - In Love`,
       SUM(responses = 6) as `Female - Like`,
       SUM(responses = 7) as `Female - Facepalm`,
       SUM(responses = 8) as `Female - Crying`
FROM answers 
. . .

然后,您可以轻松添加更多列:

SELECT DATE(created_at) as DATE,
       SUM(responses = 1) as `Male - In Love`,
       SUM(responses = 2) as `Male - Like`,
       SUM(responses = 3) as `Male - Facepalm`,
       SUM(responses = 4) as `Male - Crying`,
       SUM(responses = 5) as `Female - In Love`,
       SUM(responses = 6) as `Female - Like`,
       SUM(responses = 7) as `Female - Facepalm`,
       SUM(responses = 8) as `Female - Crying`,
       SUM(responses IN (1, 5)) as `Males + Females - In Love`),
       . . . 
FROM answers 
. . .

注意:

  • IF()已经是非标准SQL。您也可以使用MySQL更方便的“将布尔数视为数字”扩展名。
  • 仅对字符串和日期常量使用单引号。不要将它们用于列别名。