2017-04-03 77 views
1

我只是感到困惑。已經嘗試搜索整個網站或谷歌,但沒有找到'最近'的解決方案。Mysql查詢合併兩個條件成一行

好吧,讓我們說我有這個表結構。

id date  finger_id finger_time is_enter 
1 2017-03-30 2   09:00  1 
2 2017-03-30 2   17:13  0 
3 2017-03-31 4   09:10  1 
4 2017-03-31 3   09:01  1 
5. 2017-03-31 3   17:00  0 

我想使表格如下所示。

date  finger_id enter_time exit_time 
2017-03-30 2  09:00  17:13 
2017-03-30 4  09:10 
2017-03-31 3  09:10  17:00 

我已經做了sql語句,但它變成這樣。

date  finger_id enter_time exit_time 
2017-03-30 2   09:00 
2017-03-30 2      17:13 
2017-03-31 4   09:10 
2017-03-31 3   09:01 
2017-03-31 3      17:00 

我只想知道如何在finger_id列的同一日期合併is_enter 1和is_enter 0。

這是我的sql查詢引用。

SELECT * 
FROM `tbl_fingerprint` 
    LEFT JOIN `tbl_employee` ON `tbl_employee`.`fingerprint_id`=`tbl_fingerprint`.`fingerprint_id` 
    LEFT JOIN `tbl_position` ON `tbl_position`.`position_id`=`tbl_employee`.`position_id` 
WHERE `fingerprint_date` >= '2017-03-01' 
AND `fingerprint_date` <= '2017-04-01' 
GROUP BY `tbl_fingerprint`.`fingerprint_id`, 
     `tbl_fingerprint`.`fingerprint_date`, 
     `tbl_fingerprint`.`is_enter` 
ORDER BY `fingerprint_date` ASC LIMIT 30 

感謝您的幫助球員。

回答

1

你可以做一個group bydatefinger_id字段和一個聚集函數中使用條件表達式(caseif()),以獲得預期的結果。聚合函數中的條件語句只有在is_enter字段中設置了正確的值時才確保它們返回值。我離開了員工的細節,因爲那些沒有形成你的問題的一部分:

SELECT date, fingerprint_id, max(if(is_enter=1,finger_time,null) as enter_time, max(if(is_enter=0,finger_time,null) as exit_time 
FROM `tbl_fingerprint` 
WHERE `fingerprint_date` >= '2017-03-01' 
AND `fingerprint_date` <= '2017-04-01' 
GROUP BY `tbl_fingerprint`.`fingerprint_id`, 
     `tbl_fingerprint`.`fingerprint_date`, 
ORDER BY `fingerprint_date` ASC LIMIT 30 
+0

男人,這太棒了!我剛剛嘗試使用max,但我被卡住,直到我看到你的工作很棒!非常感謝。編輯:我只是將最大值改爲最小值,因爲我會得到低的結果,這太棒了! – DennisFrea

+0

已接受,感謝您的幫助,但抱歉,由於我沒有最低限度的信譽,我無法對您的答案滿意 – DennisFrea

0
SELECT * FROM `tbl_fingerprint` 
LEFT JOIN `tbl_employee` ON `tbl_employee`.`fingerprint_id`=`tbl_fingerprint`.`fingerprint_id` 
LEFT JOIN `tbl_position` ON `tbl_position`.`position_id`=`tbl_employee`.`position_id` 
LEFT JOIN (SELECT * FROM tbl_fingerprint WHERE is_enter = 0) a 
    ON a.finger_id = tbl_fingerprint.finger_id AND a.date = tbl_fingerprint.date 
WHERE `fingerprint_date` >= '2017-03-01' AND `fingerprint_date` <= '2017-04-01' AND tbl_fingerprint.is_enter = 1 
GROUP BY `tbl_fingerprint`.`fingerprint_id`, `tbl_fingerprint`.`fingerprint_date`, `tbl_fingerprint`.`is_enter` 
ORDER BY `fingerprint_date` ASC LIMIT 30 
0

試試這個(這將工作,如果finger_timetime類型): -

SELECT date, finger_id, min(finger_time) enter_time, if (min(finger_time) = max(finger_time), null, max(finger_time)) exit_time FROM xyz group by finger_id, date 
0
SELECT a1.*, a3.time as time_out FROM attendance as a1 
INNER JOIN (SELECT MIN(id) as id FROM attendance where is_enter = '1' group by date, f_id) as a2 
ON a2.id = a1.id 
LEFT JOIN attendance as a3 ON a3.date = a1.date AND a1.f_id = a3.f_id and a3.is_enter = '0' 

你可能需要投射日期以不包含時間部分或用yyyy-mm-dd格式字符