这是我的疑问:
select A_In.emp_reader_id as empId,A_In.Belongs_to,B.emp_name,A_In.DeviceSerialNumber,
DT as EntryTime,
(
select min(DT) as OutTime
from trnevents A_Out
where EVENTID like '0'
and A_Out.emp_reader_id = A_In.emp_reader_id
and A_Out.DT > A_In.DT and DATEDIFF(day,A_In.Dt,A_Out.DT)=0
) as ExitTime
from trnevents A_In
我需要从入口时间和退出时间得到计算差异。 我用了
DATEDIFF(HOUR,A_In.DT,A_out.ExitTime)
显示错误:无法绑定多部分标识符“A_out.exittime”。
任何人帮助..
答案 0 :(得分:1)
您基本上有三种选择:子查询,CTE或apply
。后者看起来像:
select A_In.emp_reader_id as empId, A_In.Belongs_to, B.emp_name, A_In.DeviceSerialNumber,
A_In.DT as EntryTime, A_Out.ExitTime,
datediff(hour, A_In.DT, A_out.ExitTime) as hourdiff
from trnevents A_In outer apply
(select min(DT) as ExitTime
from trnevents
where EVENTID = 0 and
A_Out.emp_reader_id = A_In.emp_reader_id
A_Out.DT > A_In.DT and DATEDIFF(day, A_In.Dt, A_Out.DT) = 0
) A_Out;
注意:
EVENTID
可能是一个数字。无论如何,如果您没有通配符,我建议=
而不是LIKE
。DATEDIFF()
计算小时数"转换次数"两个值之间。所以,1:59:59和2:00:01相隔一小时。通常,您希望以秒为单位取差值并除以(60 * 60)。B.emp_name
未定义。我认为这是对原始查询的错误描述。答案 1 :(得分:0)
使用交叉申请将您的思维模式应用于您的行,然后采取差异。
Select A_In.emp_reader_id as empId,A_In.Belongs_to,B.emp_name,A_In.DeviceSerialNumber,
DT as EntryTime,x.OutTime, Datediff(HOUR,a_in.DT,x.Outtime) as DifferenceTime from trnevents a_in
CROSS APPLY (select min(DT) as OutTime
from trnevents A_Out
where EVENTID like '0'
and A_Out.emp_reader_id = A_In.emp_reader_id
and A_Out.DT > A_In.DT and DATEDIFF(day,A_In.Dt,A_Out.DT)=0
) x
答案 2 :(得分:0)
我的查询中没有列A_out.exittime
列。
但我认为使用OUTER APPLY
可能会解决您的问题。
SELECT A_In.emp_reader_id AS empId,
A_In.Belongs_to,
B.emp_name,
A_In.DeviceSerialNumber,
DT AS EntryTime,
ExitTime = E.OutTime
FROM trnevents A_In
OUTER APPLY
(
SELECT MIN(DT) AS OutTime
FROM trnevents A_Out
WHERE EVENTID LIKE '0'
AND A_Out.emp_reader_id = A_In.emp_reader_id
AND A_Out.DT > A_In.DT
AND DATEDIFF(day, A_In.Dt, A_Out.DT) = 0
)E;