表 a 
id  user_id    login_time ip ..(还有字段)
1   user_001   2001-10-10  127.0.0.1
2   user_001   2001-10-10  127.0.0.1
3   user_002   2001-1-10  127.0.0.1
4   user_002   2001-1-10  127.0.0.1如上。 是用户登录信息的表结构。需要找出每个用户最后一次登录的时间。用户名,ip等等。用select user_id max(longi_time) from a group by user_id;
这样只能够查出用户名啊,我还需要ip等其他信息。
应该如何写。ps  不要想什么可以用两个字段保存登录时间,一个上次登录时间一个本次登录时间。
现在表结构已经这样了。求大侠

解决方案 »

  1.   

    select id ,user_id, login_time ,ip 
      from tablet a
     where not exists (select 1 from tablet b where a.user_id=b.user_id and b.login_time>a.login_time)
      

  2.   


    --1、
    select id ,user_id, login_time ,ip,......  
    from tab a
    where not exists (select 1 from tab b where a.user_id=b.user_id and b.login_time>a.login_time)--2、分析函数
    select id ,user_id, login_time ,ip,......
    from(
    select a.*,row_number()over(partition by a.user_id order by a.login_time desc ) rn from tab a
    )
    where rn=1
      

  3.   

    SELECT USER_ID, IP
      FROM (SELECT A.USER_ID,
                   IP,
                   ROW_NUMBER() OVER(PARTITION BY A.USER_ID ORDER BY LOGIN_TIME DESC NULLS LAST) AS RN
              FROM A) B
     WHERE B.RN = 1;
    这么查吧