cnblogs/dcrenl/SQL 排序的N种方法.html

36 lines
1023 B
HTML
Raw Permalink Normal View History

2024-09-24 12:43:01 +08:00
<div>一、手工查询得出名次</div>
<div>select * ,select count(*)+1 from T2 where T2.[成绩] &gt; T1.[成绩] as 名次 from T1</div>
<div>结果:&nbsp;</div>
<div>1</div>
<div>2</div>
<div>3</div>
<div>3</div>
<div>5</div>
<div>&nbsp;</div>
<div>二、SQL Server 2005 的排序函数 ROW_NUMBER、RANK、DENSE_RANK</div>
<div>1.ROW_NUMBER</div>
<div>select *,ROW_NUMBER() over(partition by 分组列1分组列2 ORDER BY 排序1排序2) from T</div>
<div>结果:</div>
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>&nbsp;</div>
<div>2.RANK</div>
<div>select *,RANK() over(partition by 分组列1分组列2 ORDER BY 排序1排序2) from T</div>
<div>结果:</div>
<div>1</div>
<div>2</div>
<div>3</div>
<div>3</div>
<div>5</div>
<div>&nbsp;</div>
<div>3.DENSE_RANK</div>
<div>select *,DENSE_RANK() over(partition by 分组列1分组列2 ORDER BY 排序1排序2) from T</div>
<p>&nbsp;&nbsp;结果:</p>
<div>1</div>
<div>2</div>
<div>3</div>
<div>3</div>
<div>4</div>