嗨我想创建一个SQL函数,如果列中的名称是唯一的,则返回1;否则,如果该名称不唯一,则返回1的增量。这里应该是lile:
NAME | Number
A | 1
B | 1
C | 1
C | 2
C | 3
D | 1
E | 1
我遇到的问题是让数字增加。
答案 0 :(得分:7)
ANSI SQL:
select name,
row_Number() over (partition by name order by name) as number
from your_table
答案 1 :(得分:2)
如果是SQL Server,请看这里,在C部分:使用带有PARTITION的ROW_NUMBER():
http://msdn.microsoft.com/en-us/library/ms186734.aspx
SELECT
name
, ROW_NUMBER() OVER (PARTITION BY name ORDER BY name) number
FROM tbl
答案 2 :(得分:2)
CREATE TABLE #TEST (NAME CHAR(1))
INSERT INTO #TEST
SELECT 'A'
UNION ALL
SELECT 'A'
UNION ALL
SELECT 'B'
UNION ALL
SELECT 'B'
UNION ALL
SELECT 'B'
UNION ALL
SELECT 'C'
UNION ALL
SELECT 'D'
SELECT NAME, ROW_NUMBER() OVER (PARTITION BY NAME ORDER BY NAME) AS Number
FROM #TEST