我有任务。 "对于每个订单,输入订购的单位总数和客户的名称。" 数据库:Microsoft SQL Server 12.0.2000.8 我到目前为止编写了这段代码:
SELECT a.OrderID, SUM(a.Quantity), c.CompanyName FROM [Order Details] as a
INNER JOIN Orders as b ON b.OrderID = a.OrderID
INNER JOIN Customers as c ON c.CustomerID = b.CustomerID
GROUP BY a.OrderID
但我无法显示CompanyName。每个订单应该只有一个公司名称,我们不需要连接它。我怎样才能做到这一点? 我附上我的数据库图表。
答案 0 :(得分:1)
您可能遇到的错误是所有非聚合列都应出现在GROUP BY
子句中。
所以错误基本上在CompanyName
中缺少GROUP BY
列。
因此,查询应如下所示:
SELECT
a.OrderID,
SUM(a.Quantity) as TotalQuantity,
c.CompanyName
FROM [Order Details] as a
INNER JOIN Orders as b ON b.OrderID = a.OrderID
INNER JOIN Customers as c ON c.CustomerID = b.CustomerID
GROUP BY a.OrderID, c.CompanyName