Insert into @temp3
select
Distinct t.staffName,
attendDate = convert(date,t.AttendDate)
, t.staffId
, t.Firmid
,t.ShiftName
, t.attendId
, CheckIn = convert(time(0),t.AttendDate)
, CheckOut = convert(time(0),x.AttendDate)
from @temp2 as t
outer apply (
select top 1 i.AttendDate
from @temp2 as i
where t.staffid = i.staffid
and i.attendDate > t.attendDate
order by i.attendDate desc
) x
where t.InOutMode = 'CheckIn'
[ 请检查第一张图片我想获得第一次 checkin 和最后一次 checkout
我有以下结果,我想将 checkin 和 checkout 显示为列 喜欢
-------------------------------------------------------------------------------
atteDate | staffName | staffId | Firmid |attendId | CheckIn |CheckOut |
--------------------------------------------------------------------------------
2014-11-13|Urvashi A Patel |7023 |6012 | 204 | 9:30:03 | 18:34:17
最佳答案
使用聚合查询,按 attendDate
的日期分组。
select
attendDate = convert(date,t.AttendDate)
, t.staffName
, t.staffId
, t.Firmid
, attendId = min(t.attendId)
, CheckIn = min(convert(time(0),t.AttendDate))
, CheckOut = max(convert(time(0),t.AttendDate))
from t
group by
t.staffName
, t.staffId
, t.Firmid
, convert(date,t.attendDate)
如果您收到错误是因为您尝试将其与某些可为您提供上述结果的查询一起使用,则最好在您的问题中包含该查询。
如果是这种情况,则使用 common table expression可能有帮助。
;with cte as (
/* query that does stuff to get the results in your question */
)
select
attendDate = convert(date,t.AttendDate)
, t.staffName
, t.staffId
, t.Firmid
, attendId = min(t.attendId)
, CheckIn = min(convert(time(0),t.AttendDate))
, CheckOut = max(convert(time(0),t.AttendDate))
from t
group by
t.staffName
, t.staffId
, t.Firmid
, convert(date,t.attendDate)
关于sql-server - 如何在sql server中使用像pivote结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43046216/