2014-01-10 63 views
1

考慮下面的示例數據計數分區:Sql Server中使用排序功能

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

我試圖寫一個分區按名稱+電子郵件數據的查詢,然後給了我行的索引中的每個分區和分區本身的數量(最後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

你需要一個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 
+0

謝謝匿名,那是我錯過了... –

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

+0

感謝伊恩,可惜只有一個回覆可以被標記爲答案:( –

+0

一點問題都沒有,感謝您的評論! –