如何从查询中获取有效数据

时间:2017-03-25 04:06:42

标签: sql-server

enter image description here

这是我的结果。我只想选择第一个' in'状态和第一个'最后一个'每个日期的状态,但我无法做到。

1 个答案:

答案 0 :(得分:1)

我认为使用窗口功能可以帮助您:

select * from 
(select 
 rownum = row_number() 
     over (partition by staffid, 
       convert(varchar(10), attendDate, 126), 
       status 
       order by attendDate)
 , * 
 from test
 ) x 
 where rownum = 1
 order by staffid, attendDate

每天选择最后结帐也是明智的:

select * from 
(select 
 rownum = row_number() 
     over (partition by staffid, 
       convert(varchar(10), attendDate, 126), 
       status 
       order by 
         case when status = 'in' then attendDate else 0 end,
         case when status = 'out' then attendDate else 0 end desc
       )
 , * 
 from test
 ) x 
 where rownum = 1
 order by staffid, attendDate