当前位置: 代码迷 >> Sql Server >> 怎的在数据库的一个表里筛选出每一人的时间最新的一条记录?用SQL语句。感谢大神
  详细解决方案

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

热度:90   发布时间:2016-04-24 10:06:17.0
怎样在数据库的一个表里筛选出每一人的时间最新的一条记录?用SQL语句。感谢大神啊
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

我知道用 select name,MAX(gdtime) from table1 group by yhh 挑选出每个人的最新登录实际,结果只有name,gdtime
怎么将每个人的最新登录这条记录全部信息显示出来,不止name,gdtime,我还要yhh  ,gdcs,gdsj1 这几列

以上拜托了!

------解决方案--------------------

/* 1 用子查询 */
select yhh, name, gdcs, gdsj1, gdtime
from table1
where exists
(
    select 1 from
    (
        select yhh, max(gdtime) as gdtime
        from table1 
        group by yhh
    ) x
    where x.yhh = table1.yhh 
      and x.gdtime = table1.gdtime
)

/* 2 用窗口函数 */
select * from
(
select yhh, name, gdcs, gdsj1, gdtime
, max(gdtime) over(partition by yhh) as gdtimeMax
from table1
) x
where gdtime = gdtimeMax

------解决方案--------------------


select yhh,name,gdcs,gdsj1,gdtime
from tab a where not exists(select 1 from tab where yhh=a.yhh and gdtime>a.gdtime)

------解决方案--------------------
select * from tb as t where not exists(select 1 from tb where yhh=t.yhh and  name=t. name and gdtime>t.gdtime)

------解决方案--------------------

-- 方法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
  相关解决方案