2012-10-19 100 views
0

我如何计算用户在给定日期内缺勤的总天数?mysql计算缺勤总天数

这是我如何认为它会工作的基本思路,但我无法得到工作的总部分。

SELECT total(from - until) FROM absences WHERE absences.user_id = 123 
AND absence_date_until <= '1999-12-01' AND absence_date_from >= 
'2000-12-01' 


CREATE TABLE IF NOT EXISTS `absences` (
    `absence_id` int(10) NOT NULL AUTO_INCREMENT, 
    `absence_created` datetime DEFAULT NULL, 
    `absence_date_from` datetime DEFAULT NULL, 
    `absence_date_until` datetime DEFAULT NULL, 
    `absence_status` enum('PENDING','APPROVED') NOT NULL, 
    `user_id` int(6) NOT NULL, 
    PRIMARY KEY (`absence_id`) 
) ENGINE=MyISAM DEFAULT CHARSET=utf8; 

回答

1
SELECT SUM(datediff(until, from) + 1) total_absences 
FROM absences 
WHERE absences.user_id = 123 
     AND absence_date_until <= '1999-12-01' 
     AND absence_date_from >= '2000-12-01' 
+0

这工作完美感谢。我们为什么需要'+ 1',你能解释为什么需要这部分? –

+1

DATEDIFF将给出两个日期之间的差异,所以如果你有'2012-01-01'和'2012-01-02',日期之间的差异是1.但是这将错过两天。所以你总是需要添加一个来获得缺席天数。 – Tom

0

选择DATEDIFF()IM MySQL的

SELECT datediff(absence_date_from- absence_date_until) 
FROM absences WHERE absences.user_id = 123 
AND absence_date_until <= '1999-12-01' 
AND absence_date_from >= '2000-12-01'