Sql中Rank次序函數

來源:互聯網
上載者:User

標籤:des   style   color   os   io   ar   art   div   cti   

A.對分區中的行進行排名

以下樣本按照數量對指定清單位置的清單中的產品進行了排名。

 結果集按 LocationID 分區並在邏輯上按 Quantity 排序。

 注意,產品 494 和 495 具有相同的數量。 因為它們是關聯的,所以兩者均排名第一。

 
USE AdventureWorks2012;GOSELECT i.ProductID, p.Name, i.LocationID, i.Quantity ,
RANK() OVER (PARTITION BY i.LocationID ORDER BY i.Quantity DESC) AS RankFROM Production.ProductInventory AS i INNER JOIN Production.Product AS p ON i.ProductID = p.ProductIDWHERE i.LocationID BETWEEN 3 AND 4ORDER BY i.LocationID;GO

下面是結果集:

  
ProductID   Name                   LocationID   Quantity Rank----------- ---------------------- ------------ -------- ----494         Paint - Silver                3            49       1495         Paint - Blue                  3            49       1493         Paint - Red                   3            41       3496         Paint - Yellow              3            30       4492         Paint - Black                 3            17       5495         Paint - Blue                  4            35       1496         Paint - Yellow              4            25       2493         Paint - Red                   4            24       3492         Paint - Black                 4            14       4494         Paint - Silver                4            12       5 (10 row(s) affected)
B.對結果集中的所有行排名

下面的樣本返回按薪金排名的前十名員工。 因為未指定 PARTITION BY 子句,所以,RANK 函數應用於結果集中的所有行。

  
USE AdventureWorks2012SELECT TOP(10) BusinessEntityID, Rate, RANK() OVER (ORDER BY Rate DESC) AS RankBySalaryFROM HumanResources.EmployeePayHistory AS eph1WHERE RateChangeDate = (SELECT MAX(RateChangeDate)                         FROM HumanResources.EmployeePayHistory AS eph2                        WHERE eph1.BusinessEntityID = eph2.BusinessEntityID)ORDER BY BusinessEntityID;

下面是結果集:

  
BusinessEntityID Rate                  RankBySalary---------------- --------------------- --------------------1                125.50                12                63.4615               43                43.2692               84                29.8462               195                32.6923               166                32.6923               167                50.4808               68                40.8654               109                40.8654               1010               42.4808               9

Sql中Rank次序函數

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.