我有这个表结构和一些示例数据。我想计算每个员工在月底在办公室花费的总时数,但是当我运行以下查询时,出现此错误。 希望有人能帮忙。
CREATE TABLE HOURSSPENT
(
EmpCode INT,
Time_Spent Time(5),
DayDate date
)
INSERT INTO HOURSSPENT VALUES (23, '08:30', '2018-07-12');
INSERT INTO HOURSSPENT VALUES (23, '05:40', '2018-07-13');
INSERT INTO HOURSSPENT VALUES (23, '07:23', '2018-07-16');
INSERT INTO HOURSSPENT VALUES (19, '08:30', '2018-07-12');
INSERT INTO HOURSSPENT VALUES (19, '05:40', '2018-07-13');
INSERT INTO HOURSSPENT VALUES (29, '07:23', '2018-07-12');
SELECT SUM(Time_Spent)
FROM HOURSSPENT
GROUP BY EmpCode
错误:
Msg 8117, Level 16, State 1, Line 1
Operand data type time is invalid for sum operator.
答案 0 :(得分:1)
CREATE TABLE HOURSSPENT
(
EmpCode INT,
Time_Spent Time(5),
DayDate date
)
INSERT INTO HOURSSPENT VALUES (23, '08:30', '2018-07-12');
INSERT INTO HOURSSPENT VALUES (23, '05:40', '2018-07-13');
INSERT INTO HOURSSPENT VALUES (23, '07:23', '2018-07-16');
INSERT INTO HOURSSPENT VALUES (19, '08:30', '2018-07-12');
INSERT INTO HOURSSPENT VALUES (19, '05:40', '2018-07-13');
INSERT INTO HOURSSPENT VALUES (29, '07:23', '2018-07-12');
SELECT EMPCODE,CAST(DATEADD(MILLISECOND,SUM(DATEDIFF
(MILLISECOND,0,CAST(TIME_SPENT AS DATETIME))),0) AS TIME) [sum of hrs] FROM HOURSSPENT
GROUP BY EMPCODE
输出
EMPCODE sum of hrs
19 14:10:00.0000000
23 21:33:00.0000000
29 07:23:00.0000000
答案 1 :(得分:0)
使用DATEDIFF()
以分钟为单位求出差值,然后求和。除以60可转换回小时数
SELECT EmpCode, SUM(datediff(minute, 0, Time_Spent)) / 60.0
FROM HOURSSPENT
GROUP BY EmpCode
If the total time will not exceed 24 hours, you can just simply do this
SELECT EmpCode,
convert(time, dateadd(minute, SUM(datediff(minute, 0, Time_Spent)), 0))
FROM HOURSSPENT
GROUP BY EmpCode
else, you need to calculate the day, hour, minute separately
day = Total_spent / 60 / 60