2016-12-16 77 views
0

這是我的表架構合併兩行成一米的MySQL

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 

和我如何同LOGDATE的兩行合併爲一個,這樣看的結果

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 

我在我的查詢中使用了CASE語法,但結果與想要的不一樣。當然,我的查詢有問題。這裏是我的查詢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!

回答

1

你想有條件聚集:

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; 
+0

的感謝!我還是新來的MySQL。這真的幫助了我。 – addykha