在MYSQL中对列进行分组,复杂查询

时间:2013-12-03 00:17:44

标签: mysql sql database

我有这个MYSQL查询,我需要将列分组到彼此旁边,我似乎无法做到....

SELECT Supervisor,
   (CASE WHEN DAYOFWEEK(workdate) = 2 THEN (COUNT(`ID Number`)) END) AS `Monday`,
   (CASE WHEN DAYOFWEEK(workdate) = 3 THEN (COUNT(`ID Number`)) END) AS `Tuesday`,
   (CASE WHEN DAYOFWEEK(workdate) = 4 THEN (COUNT(`ID Number`)) END) AS `Wednesday`,
   (CASE WHEN DAYOFWEEK(workdate) = 5 THEN (COUNT(`ID Number`)) END) AS `Thursday`,
   (CASE WHEN DAYOFWEEK(workdate) = 6 THEN (COUNT(`ID Number`)) END) AS `Friday`,
   (CASE WHEN DAYOFWEEK(workdate) = 7 THEN (COUNT(`ID Number`)) END) AS `Saturday`
FROM payroll.employeedatanew_copy
INNER JOIN payroll.employeehours ON employeedatanew_copy.`ID Number` = employeehours.employeeid
WHERE workdate BETWEEN "2013-10-28" AND "2013-11-02"
GROUP BY workdate, supervisor

这是我的结果: http://i.stack.imgur.com/l9kSz.png

这就是我想要的: http://i.stack.imgur.com/bRNmJ.png

1 个答案:

答案 0 :(得分:4)

我想你正在寻找这个:

SELECT Supervisor,
   COUNT(CASE WHEN DAYOFWEEK(workdate) = 2 THEN 1 END) `Monday`,
   COUNT(CASE WHEN DAYOFWEEK(workdate) = 3 THEN 1 END) `Tuesday`,
   COUNT(CASE WHEN DAYOFWEEK(workdate) = 4 THEN 1 END) `Wednesday`,
   COUNT(CASE WHEN DAYOFWEEK(workdate) = 5 THEN 1 END) `Thursday`,
   COUNT(CASE WHEN DAYOFWEEK(workdate) = 6 THEN 1 END) `Friday`,
   COUNT(CASE WHEN DAYOFWEEK(workdate) = 7 THEN 1 END) `Saturday`
FROM payroll.employeedatanew_copy
JOIN payroll.employeehours ON employeedatanew_copy.`ID Number` = employeehours.employeeid
WHERE workdate BETWEEN "2013-10-28" AND "2013-11-02"
GROUP BY supervisor

或者,count可以替换为:

SUM(DAYOFWEEK(workdate) = 2) `Monday`

这是基于MySQL true等于1这一事实,但不一定适用于其他DBMS。