id   time           usersId
1    2010-8-1       2
2    2010-8-2       2
3    2010-8-3       1
4    2010-8-4       2
5    2010-8-5       1
6    2010-8-6       2
7    2010-8-7       1
8    2010-8-8       2要求写个sql语句得到效果    2  2010-8-8
                           1  2010-8-7 
注:usersId是个外键

解决方案 »

  1.   

    要求写个sql语句得到效果   
     
    2  2010-8-8
    1  2010-8-7 
      

  2.   

    什么意思? order by  ...desc ?
      

  3.   

    本帖最后由 roy_88 于 2010-09-01 15:48:48 编辑
      

  4.   

    你用的SQL版本可能和他的不一樣
      

  5.   

    sql2000的我改成了select b.*
    from (select distinct userID from table1 )a
    cross join
    (select top 1 * from table1 where userID=a.UserID order by [time] desc)b
    但是报:列前缀 'a' 与查询中所用的表名或别名不匹配。
      

  6.   

    SQL2000用 
    SELECT * FROM   table1 AS a WHERE ID=(SELECT TOP 1 ID FROM table1 WHERE UserID=a.UserID ORDER BY [time] desc)也可用not exists
      

  7.   

    id     time      usersId
    1    2010-8-1       2
    2    2010-8-2       2
    3    2010-8-3       1
    4    2010-8-4       2
    5    2010-8-5       1
    6    2010-8-6       2
    7    2010-8-7       1
    8    2010-8-8       2
    上面是表
    然后写个sql语句查出:
    用户id       时间
    2            2010-8-8
    1            2010-8-7这个sql语句怎么写?问题就是这样。
      

  8.   

    把重复的usersId筛选掉,然后按时间排序
      

  9.   

    create table Test1(id int, [time] varchar(10),userID int)insert into Test1 
    select 1,'2010-8-1',2 union all
    select 2,'2010-8-2',2 union all
    select 3,'2010-8-3',1 union all
    select 4,'2010-8-4',2 union all
    select 5,'2010-8-5',1 union all
    select 6,'2010-8-6',2 union all
    select 7,'2010-8-7',1 union all
    select 8,'2010-8-8',2 select top 2 [time],userID from Test1 order by [time] desc
      

  10.   

    usersId不能有重复,如果我改成top6就有重复的了
      

  11.   

    需求没写清楚。top6时候,time不同,当然有重复。问题是你只需要以下的2条记录。
    用户id 时间
    2 2010-8-8
    1 2010-8-7
      

  12.   

    我现在需求就是要求usersId不能有重复的,能不能有办法解决一下~
      

  13.   

    select usersId,count(usersId) as usersId_count from jc group by usersId,usersId_count这个sql语句怎么出现usersId_count无效?
      

  14.   

     select max(time) from table where userid=2
    union all
    select max(time) from table where userid=1
      

  15.   

    use tempdb
    go
    --判断是否存在表#T
    if object_id('#T') is not null
    drop table #T--新建表#T
    create table #T(
    [id] int identity(1,1),
    [time] varchar(10),
    userId int )--添加测试值
    insert into #T([time],userId) 
    select '2010-8-1', 2 union all
    select '2010-8-2', 2 union all
    select '2010-8-3', 1 union all
    select '2010-8-4', 2 union all
    select '2010-8-5', 1 union all
    select '2010-8-6', 2 union all
    select '2010-8-7', 1 union all
    select '2010-8-8', 2--按userId分组,然后降序排列,再取时间最大的那个。
    select  userId,max([time]) as [time] from #T
    group by userId
    order by userId desc运行结果:
    -----------------------------
    userId  time
    2 2010-8-8
    1 2010-8-7