在内置函数中使用SQL列Alias?

Chr*_*ton -1 sql-server alias sql-order-by

我正在尝试根据别名订购选择,但我无法弄清楚如何.这是一个例子:

select distinct top 100 id, 
                    col1, 
                    col2, 
                    CASE WHEN @orderFormat = 'this' then col1
                         WHEN @orderFormat = 'that' then col2
                    END as orderby
from table
where col1 = like '%'
order by Len(orderby) asc, orderby asc
Run Code Online (Sandbox Code Playgroud)

每当我将别名'orderby'作为参数传递时,它都会被报告为无效列.

我的目标是能够按字母顺序排序变量列.我知道'由Len(orderby)asc命令,orderby asc有效,但只是没有别名.

任何人都知道这方面的好方法,或者我做错了什么?

谢谢!

编辑:

我已成功将select函数剥离到此:

select top 200 Clip_Name as orderby
               from Clips
order by       Len(orderby) asc, orderby asc
Run Code Online (Sandbox Code Playgroud)

Clip_Name声明为column Clip_Name(nvarchar, not null).Microsoft SQL Server 2008 R2 Edition的错误是Msg 207, Level 16, State 1, Line 1 Invalid column name 'orderby'.

但是,这有效(没有别名):

select top 200 Clip_Name 
               from Clips 
order by len(FLE_ID) desc, FLE_ID desc
Run Code Online (Sandbox Code Playgroud)

Aar*_*and 5

在使用时DISTINCT,您只能通过SELECT列表中实际存在的表达式进行排序.您不能引用不存在的列,别名或表达式.这是一种可能的解决方法,尽管简单地删除它可能实际上更好DISTINCT(如果你有两行相同,id那么你的模式或至少该列的名称存在严重错误).

select distinct top 100 id, 
                    col1, 
                    col2, 
                    CASE WHEN @orderFormat = 'this' then col1
                         WHEN @orderFormat = 'that' then col2
                    END as orderby,
    len(CASE WHEN @orderFormat = 'this' then col1
             WHEN @orderFormat = 'that' then col2
        END) AS ignore_this_column
from table
where col1 like '%'
order by ignore_this_column, orderby;
Run Code Online (Sandbox Code Playgroud)

表达得更简单,所以你不必重复表达式(也没有必要DISTINCT):

;WITH x AS 
(
  SELECT id, col1, col2, 
    orderby = CASE @orderFormat
      WHEN 'this' THEN col1
      WHEN 'that' THEN col2
    END
  FROM dbo.table
  WHERE col1 LIKE '%' -- necessary?
)
SELECT id, col1, col2
  FROM x
  ORDER BY LEN(orderby), orderby;
Run Code Online (Sandbox Code Playgroud)