Sql Server - 使用排名函数计算分区

时间:2014-01-10 22:45:04

标签: sql-server ranking-functions

考虑以下示例数据:

Name    Email  RowRank   PartitionRank
----    -----  -------   -------------
a1      e1      1         1
a1      e1      2         1
a2      e2      1         2
a2      e2      2         2
a2      e2      3         2

我正在尝试编写一个按名称+电子邮件对数据进行分区的查询,然后给出每个分区中一行的索引和分区本身的数量(最后两列列出预期的输出)。

我一直尝试使用各种查询,使用ROW_NUMBER生成RowRank很容易,但是我无法使用4个排名函数(NTILE,RANK,DENSE_RANK或ROW_RANK)中的任何一个生成分区排名。我确信这应该是可能的,但不能自己加入。

以下是一个示例查询:

SELECT Name, Email,
        ROW_NUMBER() OVER (PARTITION BY Name, Email ORDER BY Email, DisplayName) AS RowRank,
        NTILE(1) OVER (PARTITION BY Name, Email ORDER BY Email, DisplayName) AS PartitionRank
FROM Zone.MyTable

有人可以帮我解决分区排名是否正确。

3 个答案:

答案 0 :(得分:3)

整个输出需要DENSE_RANK()(无分区)

SELECT Name, Email,
        ROW_NUMBER() OVER (PARTITION BY Name, Email ORDER BY Email, DisplayName) AS RowRank,
        DENSE_RANK() OVER (ORDER BY Name, Email) AS PartitionRank
FROM Zone.MyTable

答案 1 :(得分:2)

这对我有用:

select *
  , RowRank = row_number() over (partition by Name order by Email)
  , PartitionRank = dense_rank() over (order by Name)
from MyTable

SQL Fiddle with demo

答案 2 :(得分:0)

select * ,row_number() over (order by Salary desc) as [Row_number],rank() over (order by Salary desc) as [Rank],dense_rank() over (order by Salary desc) as [Dense_rank],ntile(3) over (order by Salary desc) as [Ntile] from Employee 

检查下面给出的URL中的示例

http://www.freshcodehub.com/Article/50/implement-ranking-functions-in-sql-server