如何计算时间?这是我遇到问题的SQL:
drop table #temp
Create TABLE #Temp (EmpID varchar(50),Inout varchar(50),Punchdate datetime2(0),rowid int, INTotal datetime ,Outtotal datetime)
declare @ttt int
--truncate table @Temp
--drop table @temp
;WITH timediff AS
( select ID, In_out,Punch_Date , ROW_NUMBER() OVER ( ORDER BY Punch_date) AS [row]
-- Create an index number ordered by time.
from tblCAPdata tbl
where ID='00007971' and In_Out!='Null Mode' and CONVERT(date,Punch_Date)=CONVERT(date,'2015-12-30 00:00:00')
)
insert Into #Temp
select *,
convert(varchar(8),dateadd(mi, ISNULL(DATEDIFF(MINUTE,
(SELECT other.Punch_Date
FROM timediff Other
WHERE other.[row] = timediff.[row]-1 and In_Out='In' and In_Out!='Out' ),
timediff.Punch_Date),0),0),108)
AS INTimedifferance,
-- convert(varchar(8),dateadd(mi,datediff(Minute, day_start, day_end),0),108)
CONVERT(varchar(8),dateadd(mi, ISNULL(DATEDIFF(MINUTE,
(SELECT other.Punch_Date
FROM timediff Other
WHERE other.[row] = timediff.[row]-1 and In_Out='Out' and In_Out!='In' ),
timediff.Punch_Date),0),0),108) AS OUTTimedifferance
FROM timediff
where NOT EXISTS (
SELECT *
FROM timediff omit
WHERE omit.In_Out = timediff.In_Out
AND omit.[row] = timediff.[row] - 1
);
select sum(INTotal) as v,sum(OuttotAL) from #Temp
错误消息是:
Msg 8117, Level 16, State 1, Line 39
Operand data type datetime is invalid for sum operator.
我需要在日期时间类型
中获取时间和出时间的总和答案 0 :(得分:1)
您需要转换为秒(使用DATEDIFF)或其他时间单位,然后求和。然后,如果需要,您可以转换回日期时间。
答案 1 :(得分:1)
此方法将In和Out时间链接到每个员工IN punch的单行,计算小时数,然后让最后一个表达式执行所需的计算。
WITH TimesWithIds AS (
SELECT *,
ROW_NUMBER() OVER (PARTITION BY ID, In_Out ORDER BY Punch_Date) AS RowNum
FROM [Table] T1
), InAndOuts (
SELECT
InTimes.ID,
InTimes.Punch_Date AS PunchIn,
OutTimes.Punch_Date AS PuchOut,
CONVERT(DECIMAL(12,4), DATEDIFF(SS, InTimes.Punch_Date, OutTimes.PunchDate))/3600 AS PunchHours -- Be sure this is large enough for you
FROM TimesWithIds InTimes
INNER JOIN TimesWithIds OutTimes
ON InTimes.RowNum = OutTimes.RowNum
AND InTimes.ID = OutTimes.ID
WHERE InTimes.In_Out = 'In'
AND OutTimes.In_Out = 'Out'
)
SELECT
ID,
SUM(PunchHours) AS PunchHours
FROM InAndOuts
GROUP BY
ID
上面的示例计算每位员工的小时总小时数。添加任何过滤器并使用所需的数据格式。请记住,您不能将总小时数存储为真实日期/时间 - 必须是某种数字类型,因为24小时后,TIME数据类型才会重置。