簡體   English   中英

在內置函數中使用SQL列別名?

[英]Using SQL column Alias in built-in function?

我正在嘗試根據別名訂購一個選擇,但是我不知道如何選擇。 這是一個例子:

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

每當我將別名“ orderby”作為參數傳遞時,都將其報告為無效列。

我的目標是能夠按字母順序對可變列進行排序。 我知道'由Len(orderby)asc排序,orderby asc起作用,但不能使用別名。

有誰知道解決這個問題的好方法,或者我做錯了什么?

謝謝!

編輯:

我設法剝離選擇功能到此:

select top 200 Clip_Name as orderby
               from Clips
order by       Len(orderby) asc, orderby asc

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

使用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;

它的表達要簡單得多,因此您不必重復該表達式(也無需重復不必要的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;

根據您的第一個查詢,並根據需要刪除DISTINCT的討論,這將起作用:

select top 100 id, 
        col1, 
        col2, 
        CASE WHEN @orderFormat = 'this' then col1
             WHEN @orderFormat = 'that' then col2
        END as orderby
from t
order by Len(CASE WHEN @orderFormat = 'this' then col1
                  WHEN @orderFormat = 'that' then col2
             END) asc, orderby asc

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM