2017-09-03 163 views
1

我有MySQL员工考勤表。员工每天的第一排在时间和最后一排员工对待时间。我试图从考勤表中选择第一个和最后一个(最短时间和最长时间)。它应该给我两个排组。但我的查询并没有给我,因为我期待着结果。Mysql从每行的组中获取最大行和最小行

表(考勤)

Attendance Table with employees attendance (IMAGE)

我的查询

select *, min(attdate) as intime, max(attdate) as outtime from attendance where empid=1 

但上面的查询没有给我的预期的结果。我的输出应该在下面的图像。请给我建议查询或给我提示,以达到给定的输出。

Attendance out put should be (IMAGE)

回答

1

仅为1天的记录,这可以通过在子查询中完成条件。

SELECT * FROM attendance AS c WHERE empid=1 and (
attdate=(select min(attdate) from attendance where attendance.empid=c.empid) 
or attdate=(select max(attdate) from attendance where attendance.empid=c.empid) 
); 
0

不幸的是,MySQL不提供窗口功能,所以这是一个有点难度在这里。你可以使用存在:

Select * from yourtable t 
Where not exists (select 1 from yourtable s 
           Where t.empid = s.empid and 
             (s.attndate < t.attndate or s.attndate > t.attndate)) 

虽然它似乎你需要添加另一个条件t.date = s.date除非你已经储存在那里