sql如何分组选择显示最新的一条数据

时间:2023-03-08 20:39:25

怎样在数据库的一个表里筛选出每一人的时间最新的一条记录?用SQL语句

wenchuan408
wenchuan408 sql如何分组选择显示最新的一条数据
结帖率:100%

yhh              name    gdcs  gdsj1   gdtime
600040407    王玲    1    0.56    2011/6/21 22:34    
600040407    王玲    2    0.56    2011/6/24 10:21    
600040407    王玲    3    0.56    2011/12/7 10:45    
600040407    王玲    4    0.56    2012/1/15 14:01    
600040407    王玲    5    0.56    2012/12/26 14:11    
600040408    魏武    1    0.56    2011/6/21 22:36    
600040408    魏武    2    0.56    2013/11/15 10:46    
600040408    魏武    4    0.56    2014/1/19 9:12    
600040408    魏武    3    0.56    2014/1/10 13:57    
600040408    魏武    5    0.56    2014/1/22 10:08  
600040435    于洋    1    0.56    2011/6/22 12:54    
600040435    于洋    2    0.56    2013/3/11 9:16    
600040435    于洋    4    0.56    2014/1/10 11:18    
600040435    于洋    3    0.56    2013/12/20 15:09

-- 方法1
select a.*
from table1 a
where not exists(select 1
from table1 b
where b.name=a.name and b.gdtime>a.gdtime)

-- 方法2
select a.*
from table1 a
inner join
(select name,
max(gdtime) 'maxgdtime'
from table1
group by name) b on a.name=b.name and a.gdtime=b.maxgdtime