我有一张表:
logID eventID repID statusID logTime
174356 228985 107959 1 2013-05-03 09:25:41.000
174391 228985 107959 1 2013-05-03 10:06:33.000
174588 228985 107959 2 2013-05-03 14:59:51.000
我希望输出为
Date ClockIn ClockOut
05/03/2013 9:25:41 AM
05/03/2013 10:06:33 AM 2:59:51 PM
ie ..如果状态为1,则必须在ClockIn中,如果在ClockOut中为2。
但我得到了输出
Date ClockIn ClockOut
05/03/2013 9:25:41 AM 2:59:51 PM
05/03/2013 10:06:33 AM 2:59:51 PM
我检查过状态是2,如果时间大于时钟,则必须在时钟输出时间显示...
我的查询:
Select LTRIM(RIGHT(CONVERT(CHAR(20), rt.logTime, 22), 11)) as ClockIn,
LTRIM(RIGHT(CONVERT(CHAR(20), Min(rt1.logTime), 22), 11)) as ClockOut
from table1 rt
join table1 rt1 ON rt.repID = rt1.repID and rt1.statusID=2
AND CONVERT(nvarchar(25), rt.logTime,101) = CONVERT(nvarchar(25), rt1.logTime,101) AND rt.logTime<rt1.logTime
where rt.eventID='228985' and rt.repID='107959' and CONVERT(date, rt.logTime) = CONVERT(date, '05/03/2013')
group by rt.logTime, rt1.logTime
我应该如何得到所需的结果.........
答案 0 :(得分:1)
试试这个答案。
SELECT LTRIM(RIGHT(CONVERT(CHAR(20), rt.logTime, 22), 11)) AS ClockIn,
LTRIM(RIGHT(CONVERT(CHAR(20), Min(rt1.logTime), 22), 11)) AS ClockOut
FROM table1 rt
LEFT JOIN (
SELECT eventID,
repID,
CONVERT(DATE, logTime) LogTime,
MAX(logId) LogID
FROM table1
WHERE StatusID = 1
GROUP BY eventID,
repID,
CONVERT(DATE, logTime)
) rr
ON rt.LogId = rr.logId
LEFT JOIN table1 rt1
ON rr.repID = rt1.repID
AND rt1.statusID = 2
AND CONVERT(NVARCHAR(25), rr.logTime, 101) = CONVERT(NVARCHAR(25), rt1.logTime, 101)
AND rt.logTime < rt1.logTime
WHERE rt.StatusID = 1
AND rt.eventID = '228985'
AND rt.repID = '107959'
AND CONVERT(DATE, rt.logTime) = CONVERT(DATE, '05/03/2013')
GROUP BY rt.logTime,
rt1.logTime
<强> Fiddle demo 强>