views:

38

answers:

2

Can anybody tell me why is this query not working?

Select temp.CompanyName from

(
    SELECT  c.CompanyName, o.OrderID, 
            YEAR(o.OrderDate)  As YEAR, 
            Sum(od.UnitPrice * od.Quantity) from Orders o 
        INNER JOIN [Order Details] od 
            ON o.OrderID = od.OrderID
        INNER JOIN Customers c
            On c.CustomerID = o.CustomerID
                GROUP BY o.OrderId,c.CompanyName, YEAR(o.OrderDate)

) As temp;

It uses Northwind database. If i run it without creating a temporary view i.e if i run the query just contained within round brackets it runs just fine.

+5  A: 

at the first look i'd say because your Sum() doesn't have a column alias

Mladen Prajdic
Very Nice. You are right. But what problem could be caused just by not using column alias? If i run it without creating views it runs just fine.
Ankit Rathod
First off, this is called a subquery, not a view. Second, ask yourself how you could refer to a column without a name in the parent query, and I think you'll understand why this is an error.
Dave Markle
Oh Thanks i thought this is view, since we are select something and then selecting again from 'something'.
Ankit Rathod
+1  A: 

try this :

Select CompanyName from
(
    SELECT  c.CompanyName, o.OrderID, 
            YEAR(o.OrderDate)  As YEAR, 
            Sum(od.UnitPrice * od.Quantity) as price from Orders o 
        INNER JOIN [Order Details] od 
            ON o.OrderID = od.OrderID
        INNER JOIN Customers c
            On c.CustomerID = o.CustomerID
                GROUP BY o.OrderId,c.CompanyName, YEAR(o.OrderDate)

)  temp
Pranay Rana