3

嗨,我想创建一个 SQL 函数,如果列中的名称是唯一的,则返回 1,否则如果该名称不唯一,则返回增量 1。这应该看起来很简单:

NAME | Number
A    | 1
B    | 1
C    | 1
C    | 2
C    | 3
D    | 1
E    | 1

我遇到的问题是让数字增加。

4

3 回答 3

7

ANSI SQL:

select name,
       row_Number() over (partition by name order by name) as number
from your_table
于 2013-05-08T11:12:40.193 回答
2

如果是 SQL Server,请查看此处的 C 部分:将 ROW_NUMBER() 与 PARTITION 一起使用:

http://msdn.microsoft.com/en-us/library/ms186734.aspx

SELECT 
name
, ROW_NUMBER() OVER (PARTITION BY name ORDER BY name) number
FROM tbl
于 2013-05-08T11:04:43.247 回答
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
于 2013-05-08T11:12:25.347 回答