我正在尝试从Northwind数据库中创建每个客户每年下的订单数量的视图。但是,我在Azure Data Studio上收到错误消息“选择列表中的列'Northwind.dbo.Orders.OrderDate'无效,因为它不包含在聚合函数或GROUP BY子句中”。我的代码在下面。
CREATE OR ALTER VIEW vCustomerOrderCounts AS
SELECT
CompanyName,
Count(OrderID) AS 'NumberOfOrders',
Year(OrderDate) AS 'Order Year'
FROM Northwind.dbo.Customers, Northwind.dbo.Orders
GROUP BY CompanyName;
GO
SELECT * FROM vCustomerOrderCounts
答案 0 :(得分:0)
从不在FROM
子句中使用逗号。 始终使用正确的,明确的,标准 JOIN
语法。
您的GROUP BY
和SELECT
不兼容。另外,我强烈建议您使用不需要转义的列名:
CREATE OR ALTER VIEW vCustomerOrderCounts AS
SELECT c.CompanyName,
Count(*) AS NumberOfOrders,
Year(o.OrderDate) AS OrderYear
FROM Northwind.dbo.Customers c JOIN
Northwind.dbo.Orders o
ON c.customerId = o.customerId -- or whatever the JOIN conditions are
GROUP BY c.CompanyName, Year(o.OrderDate);