mssql - 使用内部联接在同一行中显示列值?

时间:2016-10-06 08:13:34

标签: sql sql-server join

我有一张桌子,可以为几位员工提供时间输入/输出时间:

username            datetime                 action

test.user           2016-10-05 07:30:49      0
test.user           2016-10-05 08:50:00      1
test.user           2016-10-05 08:53:49      0
test.user           2016-10-05 13:35:47      1    

我想获取每行包含用户名的结果集,以及该用户名的一对时钟输入/输出操作(0表示时钟,1表示时钟输出)。

到目前为止我所拥有的是:

select a.username, a.datetime as clockIN, b.datetime as clockOUT 
from attendance a
inner join
attendance b
on 
(
a.username = b.username
and datepart(dd, a.datetime) = datepart(dd, b.datetime)
and datepart(mm, a.datetime) = datepart(mm, b.datetime)
and datepart(yy, a.datetime) = datepart(yy, b.datetime)
and a.action = 0
and b.action = 1
and a.datetime < b.datetime
)
order by a.datetime asc

这是结果

username        clockIN                clockOUT   

test.user       2016-10-05 07:30:00    2016-10-05 08:50:00 
test.user       2016-10-05 07:30:00    2016-10-05 13:35:47    
test.user       2016-10-05 08:53:49    2016-10-05 13:35:47

期望的结果将是:

username        clockIN                clockOUT   

test.user       2016-10-05 07:30:00    2016-10-05 08:50:00   
test.user       2016-10-05 08:53:49    2016-10-05 13:35:47

有关如何从结果中省略第二行的任何想法?

谢谢!

1 个答案:

答案 0 :(得分:0)

怎么样:

SELECT
  a1.username, a1.datetime as clockIN
, (SELECT top 1 a2.datetime FROM #attendance a2
   where a1.username = a2.username and a2.action = 1 and a2.datetime > a1.datetime order by a2.datetime) AS clockout
FROM #attendance a1 WHERE action = 0