我要創建一個分組的總和,下令ROW_NUMBER列在使用SQL時:不能在ROW_NUMBER()中使用別名?
select Sales.Name, SUM(Sales.Bill) as billsum, ROW_NUMBER() over (order by billsum DESC) as rn
from Sales group by Sales.Name
它報告錯誤,因爲ROW_NUMBER在無法分析「billsum」的別名,我必須寫:
select Sales.Name, SUM(Sales.Bill) as billsum, ROW_NUMBER() over (order by SUM(Sales.Bill) DESC) as rn
from Sales group by Sales.Name
所以我在這裏寫SUM(Sales.Bill)兩次,有沒有反正在這裏使用別名?
只有通過在查詢的另一部分定義的別名,如[CTE或APPLY](http://stackoverflow.com/questions/7269195/is-it-possible-to-reuse- aggregate-functions-results-in-the-same-select/7269212#7269212)部分。 Celko解釋了爲什麼[這裏](http://joecelkothesqlapprentice.blogspot.com/2006/06/reference-alias-field-name.html) –