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

但是,尝试使用动态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.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,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.LastName)
SELECT *
FROM   T
ORDER  BY CASE
            WHEN @orderby = 'PhysicianName' THEN PhysicianName
          END,CASE
            WHEN @orderby = 'ReferralsCount' THEN ReferralsCount
          END

相关文章

发表回复

您的电子邮箱地址不会被公开。