0

我正在尝试从 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 版本中尝试时。

我现在有点迷路了。谁能告诉我我做错了什么?

谢谢!

4

2 回答 2

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
于 2012-04-16T17:56:54.983 回答
2

当存在聚合函数时,SQL Server 要求每个字段都包含在您SELECT的子句中,因此您必须将所有字段添加到您的:GROUP BYGROUP 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
于 2012-04-16T17:56:43.440 回答