SQL:在case case语句中使用别名

时间:2011-12-20 17:23:55

标签: sql-server-2008 alias

我有一个(sql server 2008)查询,如下所示:

 Select *, column1+column2 as alias1
 From complaints
 Order by 
 Case 
   When @param1 = 'filedate' then filedate
   When @param1 = 'calc' then alias1
 End

这不起作用,因为不允许在case语句中对别名进行排序,它不会识别alias1。

还有其他方法可以做到吗?

由于

3 个答案:

答案 0 :(得分:4)

要么把它放在CTE中,然后按......排序。

; with cteQuery as (Select *, column1+column2 as alias1 from complaints)
SELECT * from cteQuery Order by 
Case 
   When @param1 = 'filedate' then filedate
   When @param1 = 'calc' then alias1
 End

或者只是复制别名实际引用的内容......

Select *, column1+column2 as alias1
 From complaints
 Order by 
 Case 
   When @param1 = 'filedate' then filedate
   When @param1 = 'calc' then column1+column2
 End

答案 1 :(得分:3)

最简单的答案:

 Select complaints.*, column1+column2 as alias1
 From complaints
 Order by 
 Case 
   When @param1 = 'filedate' then filedate
   When @param1 = 'calc' then column1+column2
 End

答案 2 :(得分:2)

Select *, column1+column2 as alias1  
From complaints  
Order by   Case
     When @param1 = 'filedate' then filedate
    When @param1 = 'calc' then column1+column2
  End 

OR

SELECT *
FROM (    Select *, column1+column2 as alias1  
    From complaints ) c 
    Order by   Case
         When @param1 = 'filedate' then filedate
        When @param1 = 'calc' then alias1
      End