子查询Group By子句

时间:2014-01-13 20:01:55

标签: sql group-by subquery inner-join adventureworks

在AdventureWorks2012数据库中,我必须编写一个查询,显示Sales.SalesOrderHeader表中的所有列和Sales.SalesOrderDetail表中的平均LineTotal

尝试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.

子查询对我来说非常混乱。我究竟做错了什么?感谢。

1 个答案:

答案 0 :(得分: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