查询结果的所有行的总和

时间:2013-01-28 16:44:30

标签: sql sql-server-2005

Select (sum(OS.Small) + sum(OS.Medium)) * T.ColorPrice as TotalPrice
from Order_Colors OC
left outer join Order_Selection OS on OS.Order_ColorID = OC.Order_ColorID 
left outer join TShirtPrices T on T.Order_ColorID = OS.Order_ColorID
left outer join OrderInfo O on O.OrderID = OS.OrderID 
where O.CID = 1025
group by OC.Order_ColorID, OC.Color, O.OrderID, T.ColorPrice, T.TShirtPurchaseID

此查询为我提供了1列“总价”,大约有20行。我希望在相同的SQL查询中获取所有这些行的总和。是否可以在MS SQL 2005中使用?

2 个答案:

答案 0 :(得分:6)

在SQL Server中,您可以使用ROLLUP

Select (sum(OS.Small) + sum(OS.Medium)) * T.ColorPrice as TotalPrice
from Order_Colors OC
left outer join Order_Selection OS 
    on OS.Order_ColorID = OC.Order_ColorID 
left outer join TShirtPrices T 
    on T.Order_ColorID = OS.Order_ColorID
left outer join OrderInfo O 
    on O.OrderID = OS.OrderID 
where O.CID = 1025
group by OC.Order_ColorID, OC.Color, O.OrderID, T.ColorPrice, T.TShirtPurchaseID with ROLLUP

这将为您提供行Total Price,然后您还将获得所有值的最终总计。

答案 1 :(得分:-2)

删除查询的GROUP BY部分,您将获得一个结果。