Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to transpose mysql table rows into columns

Tags:

Here is what my current mysql table looks like:

PunchID EmpID   PunchEvent  PunchDateTime
1       0456    clockin     5/14/2013 8:36:26 AM
48      0456    breakout    5/14/2013 12:01:29 PM
53      0456    breakin     5/14/2013 12:28:31 PM
54      0456    clockout    5/14/2013 2:28:33 PM
57      0456    clockin     5/15/2013 7:38:34 AM
58      0456    breakout    5/15/2013 7:38:39 AM
59      0456    breakin     5/15/2013 7:38:41 AM
60      0456    clockout    5/15/2013 7:38:42 AM

Now I want to return a result set that is grouped based on the day of the week like so:

Day       ClockIn      BreakOut    BreakIn      ClockOut
Tuesday   8:36:26 AM  12:01:29 PM  12:28:31 PM  2:28:33 PM
Wednesday 7:38:34 AM  etc, etc...

This is my current query. But it only returns the first punch for each day.

SELECT DATE_FORMAT(PunchDateTime, '%W') as day, PunchEvent, DATE_FORMAT(PunchDateTime, '%l:%m:%s %p') as time FROM timeclock_punchlog WHERE EmpID = '0456' GROUP BY DATE(PunchDateTime) ORDER BY PunchDateTime ASC;

Can someone help me with this? Thanks Mike

like image 936
dmikester1 Avatar asked May 15 '13 14:05

dmikester1


People also ask

How do I pivot rows into columns in MySQL?

Unfortunately, MySQL does not have PIVOT function, so in order to rotate data from rows into columns you will have to use a CASE expression along with an aggregate function.

How do I pivot a table in MySQL?

The best way to create a pivot table in MySQL is using a SELECT statement since it allows us to create the structure of a pivot table by mixing and matching the required data. The most important segment within a SELECT statement is the required fields that directly correspond to the pivot table structure.


1 Answers

SELECT  DATE_FORMAT(PunchDateTime, '%W') DAY,
        MAX(CASE WHEN PunchEvent = 'ClockIn' THEN DATE_FORMAT(PunchDateTime, '%r') END) ClockIn,
        MAX(CASE WHEN PunchEvent = 'BreakOut' THEN DATE_FORMAT(PunchDateTime, '%r') END) BreakOut,
        MAX(CASE WHEN PunchEvent = 'BreakIn' THEN DATE_FORMAT(PunchDateTime, '%r') END) BreakIn,
        MAX(CASE WHEN PunchEvent = 'ClockOut' THEN DATE_FORMAT(PunchDateTime, '%r') END) ClockOut
FROM    tableName
WHERE   EmpID = 456
GROUP   BY DATE_FORMAT(PunchDateTime, '%W')
ORDER   BY PunchDateTime
  • SQLFiddle Demo

OUTPUT

╔═══════════╦═════════════╦═════════════╦═════════════╦═════════════╗
║    DAY    ║   CLOCKIN   ║  BREAKOUT   ║   BREAKIN   ║  CLOCKOUT   ║
╠═══════════╬═════════════╬═════════════╬═════════════╬═════════════╣
║ Tuesday   ║ 08:36:26 AM ║ 12:01:29 PM ║ 12:28:31 PM ║ 02:28:33 PM ║
║ Wednesday ║ 07:38:34 AM ║ 07:38:39 AM ║ 07:38:41 AM ║ 07:38:42 AM ║
╚═══════════╩═════════════╩═════════════╩═════════════╩═════════════╝
like image 159
John Woo Avatar answered Sep 22 '22 05:09

John Woo