2013-03-11 25 views
-1

我想訂購基於別名的選擇,但我無法弄清楚如何。這裏有一個例子:在內置函數中使用SQL列別名?

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 

每當我通過我的別名「排序依據」作爲一個參數,它被報告爲無效列。

我的目標是能夠以字母數字順序排列可變列。我知道'Len(order by)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 
+0

你的版本的SQL支持做到這一點? – RandomUs1r 2013-03-11 16:04:11

+0

訂購應該很好。但是當你使用'DISTINCT'時,我認爲表達式'LEN(orderby)'也必須在'SELECT'列表中。你確定你需要'DISTINCT'嗎? – 2013-03-11 16:07:11

+0

另外'col1 = like'%''沒有任何意義。即使它只是'like'%''與'1 = 1'不一樣(或者如果col1可以爲空而不是col1 IS NOT NULL)? – 2013-03-11 16:07:29

回答

1

基於你第一次查詢,下面的討論是獨特需要這將工作:

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 
+0

SPOT ON!感謝。傳說。 :) – 2013-03-12 16:49:22

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; 

表達簡單得多,這樣你就不必再重複的表達(也沒有必要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; 
+0

我已經刪除了'DISTINCT'並且包含了上面所做的排序,但它仍然說我在Len()函數中有一個「Invalid column name'order by'」。 – 2013-03-11 16:21:25

+0

您不能將'len'應用於'orderby',因爲'orderby'是一個計算出來的(或任何一個詞)列。 – 2013-03-11 22:20:39

+0

@AndriyM這是什麼意思? – 2013-03-12 12:08:39