How to add rank column?

≡放荡痞女 提交于 2021-02-20 18:56:34

问题


I would like to select records and determine rank number for each similar data.

My data is as follows.

MEMBER ID | LOAN AMOUNT 
1         | 2,000.00 
2         | 1,000.00 
3         | 4,000.00
4         | 1,000.00 

The result I wanted is shown below.

RANK|MEMBER ID|LOAN AMOUNT 
1   |3        |4,000.00
2   |1        |2,000.00
3   |2        |1,000.00
3   |4        |1,000.00 

RANK is a new column. I am using MS SQL server 2008 and created a view table as shown below but it does not resulting to what is wanted.

  select rank=count(*), s1.MemberID, s1.Loan_Amount 
   from (select MemberID, Loan_Amount from vwPrintTop20Borrowers) s1
   group by s1.MemberID, s1.LOAN_AMOUNT
     order by rank, s1.Loan_amount DESC

Please help. Thanks! :)


回答1:


SELECT ROW_NUMBER() 
        OVER (ORDER BY Loan_Amount DESC) AS Rank, 
    MemberID, LOAN_AMOUNT,
FROM vwPrintTop20Borrowers



回答2:


Just use RANK() :

SELECT RANK() OVER(ORDER BY t.loan_amount DESC) as [rank],
       t.memeber_id,t.loan_amount
FROM YourTable t

Although this will result in gaps E.G.

RANK | AMOUNT
 1        10
 2         9
 3         8
 3         8
 5         7

To avoid that, for SQL-Server 2008+ , use DENSE_RANK()

DENSE_RANK() OVER(ORDER BY t.loan_amount DESC) as [rank]



回答3:


Use below query:

Select Dense_Rank() OVER(ORDER BY [LOAN AMOUNT] DESC) as [Rank],[MEMBER ID],[LOAN AMOUNT]  
from YourTable



回答4:


   select * into #P from (
   select      1  as [MEMBER ID]        , 2000.00 as  [LOAN AMOUNT]  union   all
   select     2                      , 1000.00  union all
   select     3                         , 4000.00   union all
   select     4                         , 1000.00 
 )P


 select rank()over(  order by [LOAN AMOUNT] desc) as srno,[MEMBER ID],[LOAN AMOUNT] from #P

Output:

        srno    MEMBER ID   LOAN AMOUNT
           1          3     4000.00
           2          1     2000.00
           3          2     1000.00
           3          4     1000.00


来源:https://stackoverflow.com/questions/39388624/how-to-add-rank-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!