查询这样A表,   id     info
                           1        222 
                           1          333
                           1        444
                           1          3444
                          2            34
                           2           34
                           2              33
                            2             55
我想返回同一个id相同的前两项 ,比如id=1的只返回前两项
1   222
1   333  后面的都不要了,2的也只返回前两项。
这个怎么写呀?

解决方案 »

  1.   


    select top 2 * A group by id asc
      

  2.   

    select * from 
    (
    select px=row_number()over(partition by id order by getdate()),*  -- 如果要排序,把getdate()改成info
    from tb
    )t
    where px<3
      

  3.   

    select b.* from a cross apply(select top(2)* from a b where a.id=b.id order by info) b
      

  4.   

    select b.* from a cross apply(select top(2)* from a b where a.id=b.id order by info) b
      

  5.   

    这类情况一般用开窗函数over来的快,3楼很OK