我有一张表格,用于跟踪员工的日常入职情况。员工每天可以进行多次入住和退房。
有没有办法以某种方式显示每条记录每天都有EmployeeID
和最早的CheckIn
以及最新的CheckOut
来汇总记录。
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;
答案 0 :(得分:2)
您应该可以通过GROUP BY
和EmployeeID
上的简单DATE(CheckIn)
执行此操作,如下所示:
SELECT
EmployeeID
, DATE(CheckIn) AS the_date
, MIN(CheckIn) AS min_checkin
, MAX(CheckOut) AS max_checkout
FROM DailyEntry
GROUP BY EmployeeID, DATE(CheckIn)
注意:此查询假定所有结帐都在与相应签到的同一天发生。换句话说,午夜没人在里面。如果您需要处理夜班,查询会变得更复杂:
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