如何在日期中获得第一条记录和最后一条记录

时间:2014-09-25 08:55:17

标签: mysql

我有一个以下面的格式构建的表格:

**ID        StationID         Status        UpdateTime**
  1             1              xxxx      2014-09-25 00:01:05
  2             1              xxxy      2014-09-25 01:05:18
  3             1              xxxz      2014-09-25 09:23:05
  4             1              xxxx      2014-09-25 20:01:05
  5             1              xxxz      2014-09-25 23:21:34
  6             1              xxxz      2014-09-26 00:01:00
  7             1              xxxx      2014-09-26 01:45:24
  8             1              xxxy      2014-09-26 14:01:43
  9             1              xxxx      2014-09-26 22:01:27

对于每一天,我想选择第一条记录和最后一条记录。 结果如下:

**ID        StationID         Status        UpdateTime**
  1             1              xxxx      2014-09-25 00:01:05
  5             1              xxxy      2014-09-25 23:21:34
  6             1              xxxz      2014-09-26 00:01:00
  9             1              xxxx      2014-09-26 22:01:27

谢谢大家;

5 个答案:

答案 0 :(得分:2)

试试这个:

select *
  from YOUR_TABLE yt
  join (select min(UpdateTime) minUpdateTime, max(UpdateTime) maxUpdateTime
          from YOUR_TABLE
         group by DATE_FORMAT(UpdateTime, '%Y-%m-%d')
       ) aggyt on aggyt.minUpdateTime = yt.UpdateTime or aggyt.maxUpdateTime = yt.UpdateTime

答案 1 :(得分:1)

select * from mytable 
where UpTime = (select min(UpTime) from mytable group by date_format(UpTime,'%Y-%m-%d')) 
or UpTime = (select max(UpTime) from mytable group by date_format(UpTime,'%Y-%m-%d')) 
order by id

答案 2 :(得分:1)

select * from mytable 
where UpTime= (select min(UpTime) from mytable group by date_format(UpTime,'%Y-%m-%d')) 
or UpTime= (select max(UpTime) from mytable group by date_format(UpTime,'%Y-%m-%d')) 
order by id

答案 3 :(得分:1)

如果你想通过工会

来做这件事
SELECT ID, StationId, Status, max(UpdateTime) FROM YOUR_TABLE GROUP BY DATE(UpdateTime)
UNION ALL
SELECT ID, StationId, Status, min(UpdateTime) FROM YOUR_TABLE GROUP BY DATE(UpdateTime)

添加,为了提高效率,使用UNION ALL而不是UNION(或UNION DISTINCT),因为UNION需要带索引的内部临时表(跳过重复行),而UNION ALL将创建没有这样索引的表。

如果你想通过union和子查询来做到这一点

select * from table where id IN ( select max(id) from table GROUP BY DATE(UpdateTime) )
union all
select * from table where id IN ( select min(id) from table GROUP BY DATE(UpdateTime) )

如果你想通过子查询

来做
SELECT * from table
WHERE  id IN ( select max(id) from table GROUP BY DATE(UpdateTime) )
OR id IN ( select min(id) from table GROUP BY DATE(UpdateTime) )

答案 4 :(得分:1)

可能会有效

SELECT ID,StationId,Status,MAX(UpdateTime) FROM YOUR_TABLE GROUP BY DATE(UpdateTime)
UNION ALL
SELECT ID,StationId,Status,MIN(UpdateTime) FROM YOUR_TABLE GROUP BY DATE(UpdateTime)