这是显示问题的真实查询的简化版本。它可以在示例 Adventureworks 数据库上执行:
SELECT Person.Address.*,
(SELECT TOP 1 [Name]
FROM Person.StateProvince
WHERE Person.StateProvince.StateProvinceId = Person.Address.StateProvinceId AND Person.StateProvince.TerritoryId IN (5, 6, 7)
ORDER BY Person.StateProvince.TerritoryId) AS [Name]
FROM Person.Address
ORDER BY [Name]
这很好用,但我的问题是,如果我将排序规则添加到 order by 字段,我会收到一条奇怪的错误消息:
SELECT Person.Address.*,
(SELECT TOP 1 [Name]
FROM Person.StateProvince
WHERE Person.StateProvince.StateProvinceId = Person.Address.StateProvinceId AND Person.StateProvince.TerritoryId IN (5, 6, 7)
ORDER BY Person.StateProvince.TerritoryId) AS [Name]
FROM Person.Address
ORDER BY [Name] COLLATE Chinese_PRC_CI_AI
错误是:
Msg 207, Level 16, State 1, Line 7
Invalid column name 'Name'.
如果没有子查询,带有 collate 子句的查询效果很好,但我需要它是这样的(原因很复杂,但请相信我:))。
有谁知道为什么这个查询失败,有什么可能的解决方法?这是一个错误吗?
谢谢!亚当