views:

68

answers:

1

This is a query based on the Northwind Database in MS SQL Server 2005.

First I have to get the average of the UnitPrice from OrderDetails table, and group it by ProductID for that particular column alone and alias it as AveragePrice.

Then I need to find the maximum(AveragePrice) which is nothing but the max of previous column, how can I do it??? This is a kind of very tricky for me its taking me ages to think on it.

select
O.CustomerID,
E.EmployeeID,
E.FirstName+space(1)+E.LastName FullName,
OD.OrderID,
OD.ProductID,

(select avg(DO.UnitPrice) from OrderDetails 
    DO where OD.ProductID = DO.ProductID 
    group by DO.ProductID) AveragePrice ,

from OrderDetails OD
join Orders O
on OD.OrderID = O.OrderID

join Customers C
on C.CustomerID = O.CustomerID

join Employees E
on E.EmployeeID = O.EmployeeID

This is not a Homework question, am learning SQL, but am really stuck at this point, please help me.

+4  A: 

It's 2 steps: "the ungrouped maximum of the grouped averages"

You can expand this as needed which shows how to apply an aggregate on top of an aggregate

SELECT
    MAX(AveragePrice) AS MaxAveragePrice
FROM
    (
    select
         avg(UnitPrice) AS AveragePrice, ProductID
    from
        OrderDetails
    group by
        ProductID
    ) foo

Or with CTE

;WITH AvgStuff AS
(
    select
         avg(UnitPrice) AS AveragePrice
    from
        OrderDetails
    group by
        ProductID
)
SELECT
    MAX(AveragePrice) AS MaxAveragePrice
FROM
    AvgStuff
gbn
Am getting errors in your first implementation, please check and confirm.selectO.CustomerID,E.EmployeeID,E.FirstName+space(1)+E.LastName FullName,OD.OrderID,OD.ProductID,(select avg(DO.UnitPrice) from OrderDetails DO where OD.ProductID = DO.ProductID group by DO.ProductID) AveragePrice,select max(AveragePrice) as MaxAveragePrice from (select avg(ODD.UnitPrice) as AveragePrice from OrderDetails ODD group by ODD.ProductID) ABAfrom OrderDetails ODjoin Orders Oon OD.OrderID = O.OrderIDjoin Customers Con C.CustomerID = O.CustomerIDjoin Employees Eon E.EmployeeID = O.EmployeeID
Sorry for the bad formatting, just copy and select it from select...
atrueguy: my answer is not designed to be used as a subquery. it's complete
gbn
But how Do I solve the errors for the query which I gave.
@atrueguy: it makes no sense to group by productID and then join by orderid. Wgen grouped by productID you lose the orderid info unless you group by this too or aggregate it. Another way: the average is across all orders so it can't be used to join subsequently
gbn
@gbn: I agree - getting the MAX of all average prices is easy, but joining that to the order details really doesn't make any sense at all. @Atrueguy: what are you really trying to put together in your query? All orders in detail and maximum price per order or something?
marc_s