独特的&重复表中重复行的行号

时间:2013-10-11 01:02:32

标签: sql

我有一个名为'ID'

列的表

ID列有8行,值为100,100,100,200,200,300,300,300

我想创建一个名为'Row_ID'的新列,它应该查看ID列并为找到重复ID的每一行提供唯一的行号,并在找到不同的值时重新启动计数器。

例如,对于ID列的上述值,Row列应该看起来像

1,2,3,1,2,1,2,3

1 个答案:

答案 0 :(得分:0)

对于Oracle数据库

SELECT ROW_NUMBER() 
       OVER (PARTITION BY ID ORDER BY ID) AS "ROW_ID"
FROM (
  SELECT 100 ID FROM dual
  UNION ALL
  SELECT 100 ID FROM dual
  UNION ALL
  SELECT 100 ID FROM dual
  UNION ALL
  SELECT 200 ID FROM dual
  UNION ALL
  SELECT 200 ID FROM dual
  UNION ALL
  SELECT 300 ID FROM dual
  UNION ALL
  SELECT 300 ID FROM dual
  UNION ALL
  SELECT 300 ID FROM dual
)