TSQL CASE with if comparison in SELECT statement

CyberHawk picture CyberHawk · Jan 9, 2013 · Viewed 168.9k times · Source

I would like to use CASE statement in SELECT.

I select from user table, and (as one attribute) I also use nested SQL:

SELECT 
   registrationDate, 
   (SELECT COUNT(*) FROM Articles WHERE userId = Users.userId) as articleNumber, 
   hobbies, ...
FROM USERS

and then I would like to do a CASE statement to get rank of user (rank is dependent on articleNumber).

I tried like this:

SELECT 
   registrationDate, 
   (SELECT COUNT(*) FROM Articles WHERE Articles.userId = Users.userId) as articleNumber, 
   ranking =
      CASE
         WHEN articleNumber < 2 THEN 'Ama'
         WHEN articleNumber < 5 THEN 'SemiAma' 
         WHEN articleNumber < 7 THEN 'Good'  
         WHEN articleNumber < 9 THEN 'Better' 
         WHEN articleNumber < 12 THEN 'Best'
         ELSE 'Outstanding'
      END,
   hobbies, etc...
FROM USERS

Parsing displays no error, but when I try to run it I get error:

Msg 207, Level 16, State 1, Procedure GetUserList, Line XY
Invalid column name 'articleNumber'.

CASE doesn't "recognize" my nested SELECT, I guess.

I helped myself with some other solutions like SQL Server 2008 - Case / If statements in SELECT Clause but nothing seems to work.

I also didn't find any similar problem with '<' and '>' comparison.

Any help would be greatly appreciated ;)

Answer

TechDo picture TechDo · Jan 9, 2013

Please select the same in the outer select. You can't access the alias name in the same query.

SELECT *, (CASE
        WHEN articleNumber < 2 THEN 'Ama'
        WHEN articleNumber < 5 THEN 'SemiAma' 
        WHEN articleNumber < 7 THEN 'Good'  
        WHEN articleNumber < 9 THEN 'Better' 
        WHEN articleNumber < 12 THEN 'Best'
        ELSE 'Outstanding'
        END) AS ranking 
FROM(
    SELECT registrationDate, (SELECT COUNT(*) FROM Articles WHERE Articles.userId = Users.userId) as articleNumber, 
    hobbies, etc...
    FROM USERS
)x