我很困惑,在更改后我自己的查询工作,我使用几个表连接来计算基于他的Intime和TimeOut的员工的总加班时间。场景是Shift(S001)人员的超时时间应该只在下午17:00之后计算,无论他的时间是什么,如果他在17:00 pm以上工作,他只适用于计算OverTime。第2班(S002)加班时间为18:00。 所以我做的是我从shift表中选择了ShiftIDs,并且内部用Employee表连接它,Shift表只有3个shift id,s001,s002,s003。在员工表中,所有员工仅被分配了s001,s002。
混淆:现在当我通过像S001或S002硬编码的ShiftID那么它就可以工作,即使我像这样传递它 当SHIFTID = SHIFTID时它也有效,问题是它如何理解它在comaprison中询问哪个shiftID,两者都是SHIFTID等号,它是如何知道它是s001还是s002。在硬编码的情况下,它是可以接受的但不是动态的情况。 HELP。
查询:
with times as (
SELECT t1.EmplID
, t3.EmplName
, min(t1.RecTime) AS InTime
, max(t2.RecTime) AS [TimeOut]
, t4.ShiftId as ShiftID
, t4.StAtdTime as ShStartTime
, t4.EndAtdTime as ShEndTime
, cast(min(t1.RecTime) as datetime) AS InTimeSub
, cast(max(t2.RecTime) as datetime) AS TimeOutSub
, t1.RecDate AS [DateVisited]
FROM AtdRecord t1
INNER JOIN
AtdRecord t2
ON t1.EmplID = t2.EmplID
AND t1.RecDate = t2.RecDate
AND t1.RecTime < t2.RecTime
inner join
HrEmployee t3
ON t3.EmplID = t1.EmplID
inner join AtdShiftSect t4
ON t3.ShiftId = t4.ShiftId
group by
t1.EmplID
, t3.EmplName
, t1.RecDate
, t4.ShiftId
, t4.StAtdTime
, t4.EndAtdTime
)
SELECT
EmplID
,EmplName
,InTime
,[TimeOut]
,ShiftId
,ShStartTime
,ShEndTime
,[DateVisited]
,convert(char(5),cast([TimeOutSub] - InTimeSub as time), 108) TotalWorkingTime
,CONVERT(char(5),CASE WHEN CAST([TimeOutSub] AS DATETIME) >= ShEndTime And ShiftID = ShiftID --works even if i pass 002
Then LEFT(CONVERT(varchar(12), DATEADD(ms, DATEDIFF(ms, CAST(ShEndTime AS DATETIME), CAST([TimeOutSub] AS DATETIME)),0), 108),5)
WHEN CAST([TimeOutSub] AS DATETIME) >= ShEndTime And ShiftID = ShiftID --works even i pass 002
Then LEFT(CONVERT(varchar(12), DATEADD(ms, DATEDIFF(ms, CAST(ShEndTime AS DATETIME), CAST([TimeOutSub] AS DATETIME)),0), 108),5)
ELSE '00:00' END, 108) AS OverTime
FROM times
参见我在两种情况下使用它:CAST([TimeOutSub] AS DATETIME)&gt; = ShEndTime和ShiftID = ShiftID我有2个ShEndTime(17:00,18:00)。所以在2个比较中,它是如何知道我是否检查&gt; 17:00或18:00
答案 0 :(得分:0)
列名和绑定名如果相同..列名将被考虑用于...所以它就像1 = 1,使条件始终为真。尝试使用v_SHIDTID
示例:来自Microsoft文档。
DECLARE @var int
SET @var = 10
SELECT * FROM dbo.foo WHERE Id = @var