从mysql中创建的列中提取timediff

时间:2013-05-15 16:49:43

标签: mysql

我正在研究MySQL查询以返回一些特定结果。我很亲密。现在,我需要计算2列之间的TIMEDIFF。这是我目前的查询:

SELECT DATE_FORMAT(PunchDateTime, '%W') DAY, MAX(CASE WHEN PunchEvent = 'ClockIn' THEN DATE_FORMAT(PunchDateTime, '%r') END) AS 'Clock In', MAX(CASE WHEN PunchEvent = 'BreakOut' THEN 
    DATE_FORMAT(PunchDateTime, '%r') END) AS 'Break Out', MAX(CASE WHEN PunchEvent = 'BreakIn' THEN DATE_FORMAT(PunchDateTime, '%r') END) 'Break In', MAX(CASE WHEN PunchEvent = 'ClockOut' THEN 
    DATE_FORMAT(PunchDateTime, '%r') END) 'Clock Out', TIMEDIFF('Clock In', 'Break Out') AS Total FROM timeclock_punchlog WHERE EmpID = 456 GROUP BY 
    DATE_FORMAT(PunchDateTime, '%W') ORDER BY PunchDateTime;

现在,Total显示00:00:00。我有什么想法可以做到这一点? 谢谢 麦克

1 个答案:

答案 0 :(得分:0)

经过大量的谷歌搜索和修补,我想通了。我发现你不能在TIMEDIFF函数中使用先前在查询中创建的别名。我基本上不得不使用我用来创建别名的整个公式代替TIMEDIFF函数中的别名。 这是我的疑问:

SELECT  DATE_FORMAT(PunchDateTime, '%W') DAY, MAX(CASE WHEN PunchEvent = 'ClockIn' THEN DATE_FORMAT(PunchDateTime, '%T') END) AS 'Clock In', MAX(CASE WHEN PunchEvent = 'BreakOut' THEN DATE_FORMAT(PunchDateTime, '%T') END) AS 'Break Out', MAX(CASE WHEN PunchEvent = 'BreakIn' THEN DATE_FORMAT(PunchDateTime, '%T') END) 'Break In', MAX(CASE WHEN PunchEvent = 'ClockOut' THEN DATE_FORMAT(PunchDateTime, '%T') END) 'Clock Out', (TIMEDIFF(MAX(CASE WHEN PunchEvent = 'clockout' THEN DATE_FORMAT(PunchDateTime, '%T') END), MAX(CASE WHEN PunchEvent = 'breakin' THEN DATE_FORMAT(PunchDateTime, '%T') END))) AS Total FROM timeclock_punchlog WHERE EmpID = 456 GROUP BY DATE_FORMAT(PunchDateTime, '%W') ORDER BY PunchDateTime;

我还必须将我的%r更改为%T,以便根据军事时间而不是标准的上午/下午时间正确计算TIMEDIFF。 希望这有助于某人! 麦克