使用SQL Server,我可以使用别名来命令正常的SELECT
查询:
SELECT
u.FirstName + ' ' + u.LastName as PhysicianName, COUNT(r.Id) as ReferralsCount
FROM
Referrals r
INNER JOIN
Users u ON r.PhysicianId = u.Id
GROUP BY
r.PhysicianId, u.FirstName, u.LastName
ORDER BY
PhysicianName
但是,尝试使用动态ORDER BY
执行相同的操作:
SELECT
u.FirstName + ' ' + u.LastName as PhysicianName, COUNT(r.Id) as ReferralsCount
FROM
Referrals r
INNER JOIN
Users u ON r.PhysicianId = u.Id
GROUP
BY r.PhysicianId, u.FirstName, u.LastName
ORDER BY
CASE WHEN @orderby = 'PhysicianName' THEN PhysicianName END,
CASE WHEN @orderby = 'ReferralsCount' THEN ReferralsCount END
产生以下错误:
Msg 207,Level 16,State 1,Line 10
列名称“PhysicianName”无效。
Msg 207,Level 16,State 1,Line 11 列名称“ReferralsCount”无效。
答案 0 :(得分:13)
SELECT
中定义的列别名只能在ORDER BY
中自行使用。不在表达中。
您可以按如下方式调整原始尝试。
;WITH T
AS (SELECT u.FirstName + ' ' + u.LastName AS PhysicianName,
COUNT(r.Id) AS ReferralsCount
FROM Referrals r
INNER JOIN Users u
ON r.PhysicianId = u.Id
GROUP BY r.PhysicianId,
u.FirstName,
u.LastName)
SELECT *
FROM T
ORDER BY CASE
WHEN @orderby = 'PhysicianName' THEN PhysicianName
END,
CASE
WHEN @orderby = 'ReferralsCount' THEN ReferralsCount
END