Mysql从每行的组中获取最大行和最小行

时间:2017-09-03 10:12:24

标签: php 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)

2 个答案:

答案 0 :(得分: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 )
);

答案 1 :(得分:0)

不幸的是,MySQL不提供窗口功能,所以这里有点困难。您可以使用exists:

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,除非你只存储了1天的记录

相关问题