Ben Foster
Ben Foster

Reputation: 34800

SQL dynamic ORDER BY using alias

Using SQL Server, I can order a normal SELECT query using an alias:

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

However, attempting to do the same thing with a 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

Produces the following error:

Msg 207, Level 16, State 1, Line 10
Invalid column name 'PhysicianName'.
Msg 207, Level 16, State 1, Line 11 Invalid column name 'ReferralsCount'.

Upvotes: 2

Views: 3216

Answers (1)

Martin Smith
Martin Smith

Reputation: 452978

Column aliases defined in the SELECT can only be used in the ORDER BY on their own. Not in an expression.

You can adjust your original attempt as follows.

;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 

Upvotes: 14

Related Questions