我正在尝试从Win2000 Server SQL Server 2000 v8.00.760上运行的OLD数据库中提取一些数据,但是我收到了错误消息。我的查询正在我正在使用的当前数据库中工作,但我不知道我正在做什么,如果这是问题,那么它不会向后比较。
这是我的查询:
SELECT o.CustomerID, o.ShipName, o.ShipCity, o.ShipStateOrProvince, o.ShipPostalCode, o.ShipPhoneNumber, c.Profession, SUM( o.Total )
FROM Orders o
JOIN Customers c ON o.CustomerID = c.CustomerID
WHERE (o.OrderDate >= '2012-01-01')
AND (o.Void <> - 1)
AND (o.Cancelled <> - 1)
GROUP BY o.CustomerID
在MySQL中它工作正常。我正以我想要的方式回复查询。但我得到错误......
当我在旧版SQL中试用它时。
我现在有点迷失了。谁能告诉我我做错了什么?
谢谢!
答案 0 :(得分:3)
SQL Server对GROUP BY比MySQL更严格。 SELECT子句中的所有非聚合列也必须出现在GROUP BY中。例如,当给定CustomerID存在多个ShipName值时,这可以避免可能出现的歧义。虽然MySQL会随意选择一个,但SQL Server会强制您将它们视为单独的行。
SELECT o.CustomerID, o.ShipName, o.ShipCity, o.ShipStateOrProvince, o.ShipPostalCode, o.ShipPhoneNumber, c.Profession, SUM( o.Total )
FROM Orders o
JOIN Customers c ON o.CustomerID = c.CustomerID
WHERE (o.OrderDate >= '2012-01-01')
AND (o.Void <> - 1)
AND (o.Cancelled <> - 1)
GROUP BY o.CustomerID, o.ShipName, o.ShipCity, o.ShipStateOrProvince, o.ShipPostalCode, o.ShipPhoneNumber, c.Profession
答案 1 :(得分:2)
当存在聚合函数时,SQL服务器要求每个字段都包含在SELECT
中以包含在GROUP BY
子句中,因此您必须将所有字段添加到GROUP BY
:
SELECT o.CustomerID
, o.ShipName
, o.ShipCity
, o.ShipStateOrProvince
, o.ShipPostalCode
, o.ShipPhoneNumber
, c.Profession
, SUM( o.Total )
FROM Orders o
JOIN Customers c
ON o.CustomerID = c.CustomerID
WHERE (o.OrderDate >= '2012-01-01')
AND (o.Void <> - 1)
AND (o.Cancelled <> - 1)
GROUP BY o.CustomerID
, o.ShipName
, o.ShipCity
, o.ShipStateOrProvince
, o.ShipPostalCode
, o.ShipPhoneNumber
, c.Profession