SQL动态ORDER BY使用别名

前端之家收集整理的这篇文章主要介绍了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
原文链接:https://www.f2er.com/mssql/84257.html

猜你在找的MsSQL相关文章