问题描述:
例子就是northwind中的OrdersDetails表,只涉及单表查询。
求 总价格最大的前5位订单   
      总价格是SUM(UnitPrice*(1-Discount)*Quantity)我的思路:
1.首先利用
SELECT OrderID,SUM(UnitPrice*(1-Discount)*Quantity) as '总价格'
FROM OrderDetails 
GROUP BY OrderID
order by SUM(UnitPrice*(1-Discount)*Quantity) desc
形成结果集,如
OrderID 总价格
10865 16387.5
10981 15810
11030 12615.0498046875
10889 11380
10417 11188.4000005722
10817 10952.8449707031
10897 10835.2401733398
10479 10495.6000366211
10540 10191.6999511719
10691 10164.8000183105
........
在这个结果集的基础上,求总价格最大的前5个订单。
问题来了:
如果想用top5* from.. order by ...的格式,该怎么写?毕竟参照的是总价格,而总价格又是个聚集函数。PS:我现在只是用游标得到了结果,不用游标呢?

解决方案 »

  1.   

    SELECT top 5
      OrderID,SUM(UnitPrice*(1-Discount)*Quantity) as '总价格' 
    FROM OrderDetails 
    GROUP BY OrderID 
    order by 2 desc 
      

  2.   


    SELECT top 5
      OrderID,SUM(UnitPrice*(1-Discount)*Quantity) as '总价格' 
    FROM OrderDetails 
    GROUP BY OrderID 
    order by SUM(UnitPrice*(1-Discount)*Quantity) desc 
      

  3.   

    排名前5的用
    SELECT TOP 5 WITH TIES 
    只取5个用
    SELECT TOP 5
      

  4.   

    SELECT top 5 OrderID,SUM(UnitPrice*(1-Discount)*Quantity) as '总价格' 
    FROM OrderDetails 
    GROUP BY OrderID 
    order by 总价格 desc