我不能合并两个表

时间:2019-11-01 06:22:23

标签: mysql sql

我有一张桌子出勤 main table  我从出勤表中创建了2个视图出席视图和离开视图 查看:参加

select `dbtest`.`employee`.`empId` AS `empId`,`dbtest`.`attendance`.`timeAttendnace` AS `timeAttendnace` from (`dbtest`.`employee` left join `dbtest`.`attendance` on(`dbtest`.`attendance`.`empId` = `dbtest`.`employee`.`empId` and `dbtest`.`attendance`.`statusAttendnace` = 'In'))

view:有叶

select `dbtest`.`employee`.`empId` AS `empId`,`dbtest`.`attendance`.`timeAttendnace` AS `timeAttendnace` from (`dbtest`.`employee` left join `dbtest`.`attendance` on(`dbtest`.`attendance`.`empId` = `dbtest`.`employee`.`empId` and `dbtest`.`attendance`.`statusAttendnace` = 'Out'))

之后,我使用此代码合并了出席和离开的视图

select `attend`.`empId` AS `empId`,`attend`.`timeAttendnace` AS `clockIn`,`leaved`.`timeAttendnace` AS `clockOut` from (`dbtest`.`attend` join `dbtest`.`leaved` on(`attend`.`empId` = `leaved`.`empId`)) group by `attend`.`timeAttendnace` order by `attend`.`empId`

结果是这样的 result

我需要每位员工在同一天出席和休假

1 个答案:

答案 0 :(得分:0)

以下查询将在一行中每天向您返回员工的明智进出时间。

SELECT 
cast(TimeAttendence AS DATE),
empid,
MIN(CASE WHEN StatusAttendence = 'In' THEN TimeAttendence END) InTime,
MAX(CASE WHEN StatusAttendence = 'Out' THEN TimeAttendence END) OutTime
FROM main_table
GROUP BY cast(TimeAttendence AS DATE),empid