我想訂購基於別名的選擇,但我無法弄清楚如何。這裏有一個例子:在內置函數中使用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
你的版本的SQL支持做到這一點? – RandomUs1r 2013-03-11 16:04:11
訂購應該很好。但是當你使用'DISTINCT'時,我認爲表達式'LEN(orderby)'也必須在'SELECT'列表中。你確定你需要'DISTINCT'嗎? – 2013-03-11 16:07:11
另外'col1 = like'%''沒有任何意義。即使它只是'like'%''與'1 = 1'不一樣(或者如果col1可以爲空而不是col1 IS NOT NULL)? – 2013-03-11 16:07:29