SQL动态ORDER BY使用别名

使用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

但是,尝试使用dynamic来做同样的事情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行

无效的列名’PhysicianName’。

消息207,级别16,状态1,行11无效的列名称’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使用别名 的全部内容, 来源链接: utcz.com/qa/408789.html

回到顶部