我想选择记录并确定每个相似数据的排名。
我的数据如下。
MEMBER ID | LOAN AMOUNT
1 | 2,000.00
2 | 1,000.00
3 | 4,000.00
4 | 1,000.00
我想要的结果如下所示。
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是一个新专栏。我正在使用MS SQL Server 2008并创建了一个视图表,如下所示,但它不会产生所需的结果。
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
请帮忙。谢谢! :)
答案 0 :(得分:7)
只需使用RANK()
:
SELECT RANK() OVER(ORDER BY t.loan_amount DESC) as [rank],
t.memeber_id,t.loan_amount
FROM YourTable t
虽然这会导致间隙E.G。
RANK | AMOUNT
1 10
2 9
3 8
3 8
5 7
为避免这种情况,对于SQL-Server 2008+,请使用DENSE_RANK()
DENSE_RANK() OVER(ORDER BY t.loan_amount DESC) as [rank]
答案 1 :(得分:1)
使用以下查询:
Select Dense_Rank() OVER(ORDER BY [LOAN AMOUNT] DESC) as [Rank],[MEMBER ID],[LOAN AMOUNT]
from YourTable
答案 2 :(得分:1)
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
输出:
srno MEMBER ID LOAN AMOUNT
1 3 4000.00
2 1 2000.00
3 2 1000.00
3 4 1000.00
答案 3 :(得分:0)
SELECT ROW_NUMBER()
OVER (ORDER BY Loan_Amount DESC) AS Rank,
MemberID, LOAN_AMOUNT,
FROM vwPrintTop20Borrowers