MySQL - 检查分组结果中的任何行是否包含特定的空字段

时间:2015-04-22 20:23:57

标签: jquery mysql

我目前正在重新编写自定义PHP&基于MySQL的我公司的时钟系统。我已经提出了一个脚本,该脚本将显示每个员工的姓名,特定时期的总工作时间,并计算出他们的总薪酬。但是,我想在此结果中再添加一个字段。我希望它是一个简单的TRUE或FALSE,如果特定员工的任何行都有一个空time_out,则返回TRUE。这将在管理部分中标记他们忘记打出的员工以及计时器仍然在某处运行。

SELECT
e.eid AS eid,
CONCAT(e.last_name, ', ', e.first_name) AS full_name,
SEC_TO_TIME(SUM(IF(p.time_out IS NULL,UNIX_TIMESTAMP(),p.time_out) - p.time_in)) AS time_worked,
CONCAT('$',ROUND(SUM(IF(p.time_out IS NULL,UNIX_TIMESTAMP(),p.time_out) - p.time_in) * (e.wage/3600), 2)) AS gross_pay
FROM punches AS p
LEFT JOIN employees AS e ON e.eid = p.eid
WHERE (p.date BETWEEN '2015-01-01' AND '2015-05-05')
GROUP BY p.eid

以下是两张表。

CREATE TABLE IF NOT EXISTS `employees` (
  `eid` int(4) NOT NULL AUTO_INCREMENT,
  `first_name` tinytext NOT NULL,
  `last_name` tinytext NOT NULL,
  `status` int(1) NOT NULL DEFAULT '1',
  `vacation_start_date` date DEFAULT NULL,
  `start_date` date NOT NULL,
  `end_date` date NOT NULL DEFAULT '2100-01-01',
  `wage` decimal(6,2) NOT NULL DEFAULT '0.00',
  `deleted` int(1) DEFAULT '0',
  PRIMARY KEY (`eid`),
  UNIQUE KEY `eid` (`eid`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;

INSERT INTO `employees` (`eid`, `first_name`, `last_name`, `status`, `vacation_start_date`, `start_date`, `end_date`, `wage`, `deleted`) VALUES
    (1, 'Tom', 'Employee', 1, NULL, '2015-04-15', '2100-01-01', 22.00, 0),
    (2, 'Dave', 'Employee', 1, NULL, '2015-04-15', '2100-01-01', 10.00, 0),
    (3, 'Bill', 'Employee', 1, NULL, '2015-04-15', '2100-01-01', 10.00, 0);

CREATE TABLE IF NOT EXISTS `punches` (
  `pid` int(10) NOT NULL AUTO_INCREMENT,
  `eid` int(4) NOT NULL,
  `date` date NOT NULL,
  `time_in` int(11) DEFAULT NULL,
  `time_out` int(11) DEFAULT NULL,
  PRIMARY KEY (`pid`),
  UNIQUE KEY `pid` (`pid`)
) ENGINE=InnoDB AUTO_INCREMENT=91 DEFAULT CHARSET=utf8;

INSERT INTO `punches` (`pid`, `eid`, `date`, `time_in`, `time_out`) VALUES
    (84, 1, '2015-04-15', 1429127195, 1429127265),
    (85, 2, '2015-04-15', 1429121213, 1429127267),
    (86, 3, '2015-04-15', 1429124215, 1429127269),
    (90, 2, '2015-04-14', 1429121513, NULL);

如您所见,punches中的一行包含time_out的NULL。我想在我的结果中添加一个列,该列对ID为2的员工显示为TRUE,其余员工显示为FALSE。我该怎么做?

1 个答案:

答案 0 :(得分:1)

使用MAX(time_out IS NULL)来判断组中是否有任何空time_out值。

SELECT
    e.eid AS eid,
    CONCAT(e.last_name, ', ', e.first_name) AS full_name,
    SEC_TO_TIME(SUM(IF(p.time_out IS NULL,UNIX_TIMESTAMP(),p.time_out) - p.time_in)) AS time_worked,
    CONCAT('$',ROUND(SUM(IF(p.time_out IS NULL,UNIX_TIMESTAMP(),p.time_out) - p.time_in) * (e.wage/3600), 2)) AS gross_pay,
    IF(MAX(time_out IS NULL) = 1, 'true', 'false') AS has_empty_time_out
FROM punches AS p
LEFT JOIN employees AS e ON e.eid = p.eid
WHERE (p.date BETWEEN '2015-01-01' AND '2015-05-05')
GROUP BY p.eid