In the AdventureWorks2012 database, I have to write a query that shows all columns from the Sales.SalesOrderHeader table and the average LineTotal from the Sales.SalesOrderDetail table
Attempt 1
SELECT *
FROM Sales.SalesOrderHeader
(SELECT AVG (LineTotal)
FROM Sales.SalesOrderDetail
WHERE LineTotal <> 0)
GROUP BY LineTotal
I get the following error:
Msg 156, Level 15, State 1, Line 3
Incorrect syntax near the keyword 'SELECT'.
Msg 102, Level 15, State 1, Line 5
Incorrect syntax near ')'.
Attempt 2
SELECT *
FROM Sales.SalesOrderHeader h
JOIN (
SELECT AVG(LineTotal)
FROM Sales.SalesOrderDetail d
GROUP BY LineTotal) AS AvgLineTotal
ON d.SalesOrderID = h.SalesOrderID
I get the following error:
Msg 8155, Level 16, State 2, Line 7
No column name was specified for column 1 of 'AvgLineTotal'.
Msg 4104, Level 16, State 1, Line 7
The multi-part identifier "d.SalesOrderID" could not be bound.
Subqueries are very confusing for me. What am I doing wrong? Thanks.
Well, you're mixing your aliases and some other things.
Second version should look like that
SELECT h.*, d.avgLineTotal
FROM Sales.SalesOrderHeader h
JOIN (
SELECT SalesOrderID, --you need to get this to make a join on it
AVG(LineTotal)as avgLineTotal --as stated by error, you have to alias this (error 1)
FROM Sales.SalesOrderDetail
GROUP BY SalesOrderID) d --this will be used as subquery alias (error 2)
ON d.SalesOrderID = h.SalesOrderID
another solution would be
select h.field1, h.field2, -- etc. all h fields
coalesce(AVG(sod.LineTotal), 0)
from Sales.SalesOrderHeader h
LEFT JOIN Sales.SalesOrderDetail d on d.SalesOrderID = h.SalesOrderID
GROUP BY h.field1, h.field2 --etc. all h fields
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.