有个表,字段是a int,b int,c datetime
假设数据有:
a b c
1 1 
2 1 
3 1
4 1
1 2
2 2
3 2
4 2
(C时间字段数据未列出)
现在想从表中读取a b c,并且b为1和2的各两条按C排序的最新的纪录
分别查询的话:
select top 2 a,b,c from table where b=1 order by c
select top 2 a,b,c from table where b=2 order by c
即可,但能否用一行来实现?

解决方案 »

  1.   

    最简单的办法就是在
    select top 2 a,b,c from table where b=1 order by c
    select top 2 a,b,c from table where b=2 order by c
    两条语句中间加个union all~
      

  2.   


    --方法一
    Select * From 表 A Where Not Exists(Select c From 表 Where b = A.b And c > A.c)--方法二
    Select * From 表 A Where c = (Select Max(c) From 表 Where b = A.b)--方法三
    Select A.* From 表 A 
    Inner Join
    (Select b, Max(c) As c From 表 Group By b) B
    On A.b = B.b And A.c = B.c
      

  3.   

    SELECT id identity(int,1,1),* into #temp from tableselect * from #temp 
    where id in (select id from #temp where b=1 order by c) or
    id in (select id from #temp where b=1 order by c)
      

  4.   

    -改一下!
    SELECT identity(int,1,1) id ,* into #temp from tableselect * from #temp 
    where id in (select top 2 id from #temp where b=1 order by c) or
    id in (select top 2  id from #temp where b=2 order by c)
      

  5.   

    paoluo(一天到晚游泳的鱼)这个方法只能搜索各1条纪录,是否sql server只能如此?mugua604(熟不了的木瓜)纪录很多的情况下,这个方法不太现实吧