作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
使用 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
Invalid column name 'PhysicianName'.
Msg 207, Level 16, State 1, Line 11 Invalid column name 'ReferralsCount'.
最佳答案
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
关于SQL 动态 ORDER BY 使用别名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18105354/
我是一名优秀的程序员,十分优秀!