将第一个查询中的totalorderprice除以第二个查询中的totalorders

时间:2014-04-25 10:42:35

标签: sql-server sql-server-2008 tsql

如何将第一个查询中的totalorderprice与第二个查询中的totalorders分开,并将结果保存在新列中

第一次查询:

SELECT o.OrderID,SUM((od.UnitPrice * od.Quantity) - (od.Discount/100))+ o.Freight AS TotalOrderPrice
FROM [Order Details] as od join Orders as o on o.OrderID=od.OrderID
GROUP BY o.OrderID, o.Freight

第二次查询:

SELECT distinct o.employeeid, count(o.OrderID)as totalorders 
FROM Orders o 
GROUP BY o.EmployeeID

2 个答案:

答案 0 :(得分:1)

试试这个

SELECT *,TotalOrderPrice/totalorders As FinalTotal FROM
(
SELECT o.OrderID,SUM((od.UnitPrice * od.Quantity) - (od.Discount/100))+ o.Freight AS TotalOrderPrice
FROM [Order Details] as od join Orders as o on o.OrderID=od.OrderID
GROUP BY o.OrderID, o.Freight
) S JOIN
(
SELECT Distinct o.employeeid, max(OrderId) as OrderID,Count(o.OrderID)as totalorders 
FROM Orders o 
GROUP by o.EmployeeID
) ON S.OrderID= T.OrderID

答案 1 :(得分:0)

或者您可以使用CROSS APPLY。

    SELECT o.OrderID,SUM((od.UnitPrice * od.Quantity) - (od.Discount/100))+ o.Freight AS TotalOrderPrice, sp.cnt
    FROM [Order Details] AS od
        INNER JOIN Orders AS o ON  o.OrderID = od.OrderID
        CROSS APPLY (SELECT COUNT(*) cnt FROM Orders WHERE employeeid = o.employeeid) sp
    GROUP BY o.OrderID, o.Freight

这也以另一种方式使用CROSS APPLY

SELECT o.OrderID, tot.TotalOrderPrice, 
    sp.cnt, tot.TotalOrderPrice/sp.cnt 'NewField'
    FROM Orders o 
        CROSS APPLY (SELECT COUNT(*) cnt FROM Orders WHERE employeeid = o.employeeid) sp
        CROSS APPLY (SELECT SUM((UnitPrice * Quantity) - (Discount/100)) AS Subtotal FROM [Order Details] od WHERE OrderID = o.OrderID) od
        CROSS APPLY (SELECT od.Subtotal + o.freight TotalOrderPrice) tot