2011/04/18

查詢結果加入序號


今天遇到了這個問題,希望在查詢結果中加入序號;那這邊就筆記一下。
一、ROW_NUMBER:會根據宣告的排序資料行進行輸出,並產生序號
定義:ROW_NUMBER() ( [ <分割子句> ] <排序的子句> )
1.

select SalesOrderID,CustomerID,
ROW_NUMBER() over (order by CustomerID) '序號'
FROM Sales.SalesOrderHeader
WHERE SalesOrderID > 10000
Order By CustomerID

2011-04-19_100817

2.



select SalesOrderID,CustomerID,
ROW_NUMBER() over (partition by CustomerID order by CustomerID) '序號'
FROM Sales.SalesOrderHeader
WHERE SalesOrderID > 10000
Order By CustomerID

2011-04-19_100955





二、RANK:產生序號過程中,遇到相同資料值使用相同號碼,跨群組時會「跳號」處理

定義:RANK() ( 排序子句 )



select SalesOrderID,CustomerID,
RANK() over (order by CustomerID) '跨群組跳號'
FROM Sales.SalesOrderHeader
WHERE SalesOrderID > 10000
Order By CustomerID


2011-04-19_102042





三、DENSE_RANK:產生序號過程中,遇到相同資料值使用相同號碼,跨群組時會「連號」處理



定義:DENSE_RANK ( 排序子句 )



select SalesOrderID,CustomerID,
DENSE_RANK() over (order by CustomerID) '跨群組續號'
FROM Sales.SalesOrderHeader
WHERE SalesOrderID > 10000
Order By CustomerID


2011-04-19_102559 



另外還有其他產生序號函數


NTILE (Transact-SQL)


Ranking Functions (Transact-SQL)


Built-in Functions (Transact-SQL)

0 Comments:

張貼留言