Northwind表中:select * from [order details] ,我想查出每个orderid的前3个数据该怎么写呀?是只显示每个orderid的前3条。

解决方案 »

  1.   

    select * from [order details] T1
    where 3>(select count(1) from [order details] T2 where T2.orderid=T1.orderid and T2.ProductID<T1.ProductID)
      

  2.   

    select * from [order details] a 
    where (select count(1) from [order details] b where b.orderid=a.orderid and b.c_? <= a.c_?) <= 3
      

  3.   


    --每个货品的前3条
    select * from [order details] a
    where 3>(SELECT COUNT(*) FROM [order details] b WHERE a.ProductID<b.ProductID and a.OrderID=b.OrderID)
      

  4.   

    ----求每个OrderID的Quantity最大的前三名
    select * from Northwind..[order details] a 
    where (select count(*) from  Northwind..[order details] where orderid = a.orderid and quantity > a.quantity) < 3
    ----求每个OrderID的前三行
    if object_id('tempdb..#tmp') is not null
    drop table #tmp
    select id = identity(int,1,1),* into #tmp from Northwind..[order details]
    select * from #tmp a
    where (select count(*) from  #tmp where orderid = a.orderid and id < a.id) < 3
    drop table #tmp
      

  5.   

    1 select  * from tab
      where  orderid in (select top 3 orderid  from  tab a where a.pk = pk order by orderid desc)2 select * from tab
      where not exists (select 1 from tab a where a.pk = pk and  orderid < b.orderid having count(1) < 3)