SELECT
使用 SQL Server,我可以使用别名订购普通查询:
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
产生以下错误:
消息 207,级别 16,状态 1,第 10 行
无效的列名称“医师姓名”。
消息 207,级别 16,状态 1,第 11 行无效的列名称“ReferralsCount”。