Предложение группы подзапросов по

В базе данных AdventureWorks2012 мне нужно написать запрос, который показывает все столбцы из таблицы Sales.SalesOrderHeader и среднее значение LineTotal из таблицы Sales.SalesOrderDetail.

Попытка 1

SELECT * 
FROM Sales.SalesOrderHeader
    (SELECT AVG (LineTotal) 
    FROM Sales.SalesOrderDetail
    WHERE LineTotal <> 0)
GROUP BY LineTotal

Я получаю следующую ошибку:

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 ')'.

Попытка 2

SELECT *
FROM Sales.SalesOrderHeader h
    JOIN (
    SELECT AVG(LineTotal)
    FROM Sales.SalesOrderDetail d
    GROUP BY LineTotal) AS AvgLineTotal
ON d.SalesOrderID = h.SalesOrderID

Я получаю следующую ошибку:

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.

Подзапросы меня очень сбивают с толку. Что я делаю неправильно? Спасибо.


person user3047713    schedule 13.01.2014    source источник
comment
Давай, ты собираешься просить всех своих заданий? stackoverflow.com/questions/21096582/sql-subqueries-errors, stackoverflow.com/questions/20501110/, stackoverflow.com/questions/20499184/sql-total -количество-и-сумма   -  person Lamak    schedule 14.01.2014


Ответы (1)


Ну, вы смешиваете свои псевдонимы и некоторые другие вещи.

Вторая версия должна выглядеть так

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

другое решение было бы

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
person Raphaël Althaus    schedule 13.01.2014