小编典典

SQL动态ORDER BY使用别名

sql

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


阅读 560

收藏
2021-03-17

共1个答案

小编典典

中定义的列别名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
2021-03-17