需要按计数器分组返回列

时间:2013-06-18 12:07:02

标签: sql-server tsql

我有一张桌子:

declare @tbl as table (
  Name nvarchar(10), Property int
)

表格中的示例数据如下:

Name | Property
'A'  | 0
'A'  | 1
'A'  | 2
'A'  | 3
'B'  | 0
'B'  | 2
'B'  | 1
'C'  | 0

如何将此表与列一起返回,该列描述了分组列索引?

预期结果:

Name | Property | Index
'A'  | 0        | 1
'A'  | 1        | 1
'A'  | 2        | 1
'A'  | 3        | 1
'B'  | 0        | 2
'B'  | 2        | 2
'B'  | 1        | 2
'C'  | 0        | 3

请建议!谢谢!

更新

我使用dense_rank()(我想是以错误的方式),就像这样

SELECT 
   *, 
   DENSE_RANK() OVER (PARTITION BY [Name] ORDER BY [Property]) AS R
FROM @tbl

2 个答案:

答案 0 :(得分:4)

使用DENSE_RANK:

select *
  , [Index] = dense_rank() over (order by Name)
from tbl

SQL Fiddle with demo

答案 1 :(得分:1)

尝试这样......

Select Name,Property ,Dense_Rank() OVER 
    (ORDER BY Name) AS [Index] from TableName