44

我想在 SELECT 中使用 CASE 语句。

我从用户表中选择,并且(作为一个属性)我还使用嵌套 SQL:

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

然后我想做一个 CASE 语句来获取用户的排名(排名取决于 articleNumber)。

我试过这样:

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

解析显示没有错误,但是当我尝试运行它时出现错误:

消息 207,级别 16,状态 1,过程 GetUserList,行 XY
列名称“articleNumber”无效。

我猜,CASE 不能“识别”我的嵌套 SELECT。

我帮助自己解决了一些其他解决方案,例如 SQL Server 2008 - SELECT 子句中的 Case / If 语句, 但似乎没有任何效果。

'<' 和 '>' 比较我也没有发现任何类似的问题。

任何帮助将不胜感激 ;)

4

3 回答 3

57

请在外部选择中选择相同的。您无法在同一查询中访问别名。

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
于 2013-01-09T08:53:57.380 回答
9

应该:

SELECT registrationDate, 
       (SELECT CASE
        WHEN COUNT(*)< 2 THEN 'Ama'
        WHEN COUNT(*)< 5 THEN 'SemiAma' 
        WHEN COUNT(*)< 7 THEN 'Good'  
        WHEN COUNT(*)< 9 THEN 'Better' 
        WHEN COUNT(*)< 12 THEN 'Best'
        ELSE 'Outstanding'
        END as a FROM Articles 
        WHERE Articles.userId = Users.userId) as ranking,
        (SELECT COUNT(*) 
        FROM Articles 
        WHERE userId = Users.userId) as articleNumber,
hobbies, etc...
FROM USERS
于 2013-01-09T09:00:04.447 回答
0

你可以试试这个:

WITH CTE_A As (SELECT COUNT(*) as articleNumber,A.UserID  as UserID FROM Articles A
           Inner Join Users U
           on  A.userId = U.userId 
           Group By A.userId , U.userId   ),

B as (Select us.registrationDate,

      CASE
         WHEN CTE_A.articleNumber < 2 THEN 'Ama'
         WHEN CTE_A.articleNumber < 5 THEN 'SemiAma' 
         WHEN CTE_A.articleNumber < 7 THEN 'Good'  
         WHEN CTE_A.articleNumber < 9 THEN 'Better' 
         WHEN CTE_A.articleNumber < 12 THEN 'Best'
         ELSE 'Outstanding'
         END as Ranking,
         us.hobbies, etc...
         FROM USERS Us Inner Join CTE_A 
         on CTE_A.UserID=us.UserID)

Select * from B
于 2014-09-30T05:19:44.337 回答