SQL选择每天最早的开始日期时间和最新结束日期时间

时间:2013-12-04 20:32:34

标签: mysql sql datetime select

我有一张表格,用于跟踪员工的日常入职情况。员工每天可以进行多次入住和退房。 有没有办法以某种方式显示每条记录每天都有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;

1 个答案:

答案 0 :(得分:2)

您应该可以通过GROUP BYEmployeeID上的简单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