像SQL Server

时间:2015-07-03 15:30:28

标签: sql sql-server sql-server-2008

如何在SQL Server中编写查询,例如rank(),但计算方法有点不同。

例如,排名是:

rankNumber uniqeId
1             160 
2             159
3             158
4             157
5             156
5             156
7             152
8             151
8             151
10            150

我需要这样的结果:

rankNumber uniqeId
1           160
2           159
3           158
4           157
5           156
5           156
6           152
7           151
7           151
8           150

我该怎么做? SQL Server中有这样的功能吗?

2 个答案:

答案 0 :(得分:4)

SELECT DENSE_RANK() OVER (ORDER BY TotCnt DESC) AS TopCustomers, CustomerID, TotCnt

FROM (SELECT CustomerID, COUNT(*) AS TotCnt

FROM Orders Group BY CustomerID) AS Cust

<强>输出

enter image description here

答案 1 :(得分:0)

要扩展DENSE_RANK评论,完整查询简短而且甜蜜:

SELECT
  DENSE_RANK() OVER (ORDER BY uniqueId DESC) AS rankNumber,
  uniqueId
FROM myTable
ORDER BY rankNumber

有一个SQL小提琴here