简体   繁体   中英

Merge two rows into one row mysql

this is my table schema

id | name | number | status | logtime | logdate
 1    John    1001     in     8:00 AM   10/01/2016
 2    John    1001     out    5:00 PM   10/01/2016
 3    Carl    1002     in     8:01 AM   10/01/2016
 4    John    1001     in     8:00 AM   10/02/2016
 5    John    1001     out    5:00 PM   10/02/2016

and how do i merge the two rows of the same logdate into one, looking like this as result

name | number | time_in | time_out | logdate
John    1001    8:00 AM   5:00 PM    10/01/2016
John    1001    8:00 AM   5:00 PM    10/02/2016
Carl    1002    8:01 AM     NULL     10/01/2016

i used CASE syntax on my query but the result isn't the same as a wanted to. Surely, there's something wrong with my query. Here's my query btw:

SELECT
   number,
   name,
   CASE status WHEN 'in' THEN logtime END AS time_in,
   CASE status WHEN 'out' THEN logtime END AS time_out,
   LogDate
FROM
   tbl_attendanceraw
Group by logdate

TIA!

You want conditional aggregation:

SELECT number, name,
       MAX(CASE status WHEN 'in' THEN logtime END) AS time_in,
       MAX(CASE status WHEN 'out' THEN logtime END) AS time_out,
       LogDate
FROM tbl_attendanceraw
Group by logdate, number, name;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM