我需要计算一些工人在2014年花费的时间,并且需要按月分组(和总和)。 每一行都应该是这样的
Worker 1 | Tot Time HH:MM:SS (Jan) | Tot Time HH:MM:SS (Feb) | etc... | Tot Time Year
Worker 2 | Tot Time HH:MM:SS (Jan) | Tot Time HH:MM:SS (Feb) | etc... | Tot Time Year
Worker 3 | Tot Time HH:MM:SS (Jan) | Tot Time HH:MM:SS (Feb) | etc... | Tot Time Year
我的MySQL数据库是这样的:
id_worker (int, primary key), in_datetime (DATETIME), out_datetime (DATETIME)
有人可以帮帮我吗?我只设法计算一年内的总时间。
非常感谢!
答案 0 :(得分:2)
试试这个:
SELECT id_worker,
SEC_TO_TIME(SUM(CASE WHEN MonthNo = 1 THEN workingTime ELSE 0 END)) AS JanWorkingTime,
SEC_TO_TIME(SUM(CASE WHEN MonthNo = 2 THEN workingTime ELSE 0 END)) AS FebWorkingTime,
SEC_TO_TIME(SUM(CASE WHEN MonthNo = 3 THEN workingTime ELSE 0 END)) AS MarWorkingTime,
SEC_TO_TIME(SUM(CASE WHEN MonthNo = 4 THEN workingTime ELSE 0 END)) AS AprWorkingTime,
SEC_TO_TIME(SUM(CASE WHEN MonthNo = 5 THEN workingTime ELSE 0 END)) AS MayWorkingTime,
SEC_TO_TIME(SUM(CASE WHEN MonthNo = 6 THEN workingTime ELSE 0 END)) AS JunWorkingTime,
SEC_TO_TIME(SUM(CASE WHEN MonthNo = 7 THEN workingTime ELSE 0 END)) AS JulWorkingTime,
SEC_TO_TIME(SUM(CASE WHEN MonthNo = 8 THEN workingTime ELSE 0 END)) AS AugWorkingTime,
SEC_TO_TIME(SUM(CASE WHEN MonthNo = 9 THEN workingTime ELSE 0 END)) AS SepWorkingTime,
SEC_TO_TIME(SUM(CASE WHEN MonthNo = 10 THEN workingTime ELSE 0 END)) AS OctWorkingTime,
SEC_TO_TIME(SUM(CASE WHEN MonthNo = 11 THEN workingTime ELSE 0 END)) AS NovWorkingTime,
SEC_TO_TIME(SUM(CASE WHEN MonthNo = 12 THEN workingTime ELSE 0 END)) AS DecWorkingTime
FROM (SELECT id_worker, MONTH(in_datetime) MonthNo,
SUM(TIMESTAMPDIFF(SECOND, in_datetime, out_datetime)) AS workingTime
FROM tableA
WHERE YEAR(in_datetime) = 2014
GROUP BY id_worker, MonthNo
) AS A
GROUP BY id_worker