I have a table as follows for tracking employee daily entry. An employee can has multiple check in and out a day. Is there a way to display in a way such that each record has the EmployeeID
and respective earliest CheckIn
and latest CheckOut
of each day to summarize the record.
CREATE TABLE IF NOT EXISTS `PhyMeS_schema`.`DailyEntry` (
`EmployeeID` VARCHAR(10) NOT NULL,
`CheckIn` DATETIME NOT NULL,
`CheckOut` DATETIME NULL,
PRIMARY KEY (`EmployeeID`, `CheckIn`),
CONSTRAINT `fk_dailyEntry_EmployeeID`
FOREIGN KEY (`EmployeeID`)
REFERENCES `PhyMeS_schema`.`Employee` (`EmployeeID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
You should be able to do this with a simple GROUP BY
on EmployeeID
and DATE(CheckIn)
, like this:
SELECT
EmployeeID
, DATE(CheckIn) AS the_date
, MIN(CheckIn) AS min_checkin
, MAX(CheckOut) AS max_checkout
FROM DailyEntry
GROUP BY EmployeeID, DATE(CheckIn)
Note: this query assumes that all checkouts happen on the same day as their corresponding check-ins. In other words, nobody is inside on midnight. If you need to deal with night shifts, the query becomes more complex:
SELECT EmployeeID, the_date, MIN(min_checkin), MAX(max_checkout)
FROM (
SELECT EmployeeID, DATE(CheckIn) AS the_date, MIN(CheckIn) AS min_checkin, null as max_checkout
FROM DailyEntry
GROUP BY EmployeeID, DATE(CheckIn)
UNION ALL
SELECT EmployeeID, DATE(CheckOut) AS the_date, null AS min_checkin, MAX(CheckOut) as max_checkout
FROM DailyEntry
GROUP BY EmployeeID, DATE(CheckOut)
) GROUP BY EmployeeID, the_date
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.