这是显示问题的真实查询的简化版本。它可以在示例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]
这很好用,但我的问题是,如果我按字段添加排序规则,我会收到一条奇怪的错误消息:
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子句的查询效果很好,但是我需要它是这样的(出于一个复杂的原因,但请相信我:)。
是否有人知道此查询失败的原因,以及可能的解决方法是什么?这是一个错误吗?
谢谢! 亚当
答案 0 :(得分:2)
SQL Server不允许您在order by子句中通过别名引用列。例如,这不起作用:
select id+1 as x from MyTable order by x
但您可以通过重复列定义来解决这个问题:
select id+1 as x from MyTable order by id+1
或者使用子查询:
select * from (select id+1 as x from MyTable) as subquery order by x
在您的情况下,最好的修复可能是使用子查询:
SELECT *
FROM (
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
) as SubqueryAlias
ORDER BY
[Name]