0

I have this MYSQL Query and I need the columns to be grouped up next to eachother, I just can't seem to do it....

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

Here is my result: https://i.sstatic.net/l9kSz.png

This is what I want: https://i.sstatic.net/bRNmJ.png

4
  • In the "what I want" image, the value for each row is that same for each workday, is that what is expected? Commented Dec 3, 2013 at 0:22
  • Remove the workdate field from the group by. Commented Dec 3, 2013 at 0:22
  • @MikeBrant, yeah I had just used the same dataset for each date, so values are the same :). Commented Dec 3, 2013 at 0:51
  • Thanks Barranka, but that just wasn't enough, perfect answer is below! Commented Dec 3, 2013 at 0:51

1 Answer 1

4

I guess you're looking for this:

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

Alternatively, the counts could be replaced with:

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

This works based on the fact that true equals 1 in MySQL but will not necessarily work in other DBMS.

Sign up to request clarification or add additional context in comments.

2 Comments

It should be noted that grouping by workdate basically put all workdate=2 rows first, then workdate=3 rows, etc. You don't want that grouping at all.
Right. That's why Darrent Bent was there more than once in different rows.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.