正如@Gordon Linoff 评论的那样,您需要创建一个包含您的营业时间的表格:
CREATE TABLE business_days (
start DATETIME NOT NULL,
end DATETIME NOT NULL
);
INSERT INTO `business_days`
(start, end)
VALUES
('2011-12-30 09:00', '2011-12-30 15:00'), -- short day
('2012-01-03 09:00', '2012-01-03 17:00'), -- 31st, 1st were Sat/Sun
('2012-01-04 09:00', '2012-01-04 17:00'), -- 2nd was a public holiday
('2012-01-05 09:00', '2012-01-05 17:00'),
-- etc.
然后你可以这样做:
SELECT m.*,
SEC_TO_TIME(SUM(TIME_TO_SEC(TIMEDIFF(
LEAST(m.updated, b.end),
GREATEST(m.created, b.start)
))))
FROM my_table m JOIN business_days b
ON b.start < m.updated AND m.created < b.end
GROUP BY m.created, m.updated -- or some other key into my_table
在sqlfiddle上查看。