列中值的出现的标签号

时间:2016-08-09 11:19:56

标签: sql

我有下表,tempTable:

Id     | Type
--------------
01       L
23       D
45       L
67       L
89       L

我希望能够添加一个新列,该列逐步计算每个行类型在其上方的表格中出现的数量。在上面的示例中,我希望输出看起来像这样:

Id     | Type       | Type Count
-------------------------------- 
01       L            L 1
23       D            D 1
45       L            L 2
67       L            L 3
89       L            L 4

任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:2)

使用 Row_Number 然后分区

SELECT
Id,
Type,
[Type]+ ' '+CAST(Row_Number() OVER (partition by [Type] order by id) AS VARCHAR(5)) as 'Type Count'
FROM 
TableName
Order by Id

答案 1 :(得分:0)

没有row_number()的解决方案:

SELECT tn.Type, tn.Type || '-' || 
(SELECT  1+COUNT(Type) FROM TableName 
   WHERE id < tn.id AND Type = tn.Type) AS number_of_occurrences 
FROM TableName tn