使用 WITH OVER 或使用其他方法,如何为另一组记录启动新序列号?
是SQL Server 2005。
E.g。如何获得以下输出(我在预期输出中讨论RowNum列)?
表:
id名称
100 A
200 B
300 C
200 B
200 B
预期产量:
RowNum id
1 100
1 200
2 200
3 200
1 300
答案 0 :(得分:4)
你正在寻找PARTITION BY,测试一下。
Create table #test
(
i int
)
INSERT INTO #test
SELECT 100 UNION ALL
SELECT 200 UNION ALL
SELECT 300 UNION ALL
SELECT 200 UNION ALL
SELECT 200
SELECT I, ROW_NUMBER() OVER (PARTITION BY I ORDER BY i ASC) FROM #test
答案 1 :(得分:2)
ROW_NUMBER() OVER (PARTITION BY ... ORDER BY ...)
您的示例没有明确的ORDER BY或PARTITION BY预期输出。两者都可以是id
,也可以是name
。一个更好的例子是:
表:
id type
1 100
2 200
3 300
4 200
5 200
预期:
rn id type
1 1 100
1 2 200
2 4 200
3 5 200
1 3 300
对应ROW_NUMBER() OVER (PARTITION BY type ORDER BY id)
答案 2 :(得分:1)
declare @MyTable table (
id int,
name char(1)
)
insert into @MyTable
(id, name)
values
(100,'A')
insert into @MyTable
(id, name)
values
(200,'B ')
insert into @MyTable
(id, name)
values
(300,'C')
insert into @MyTable
(id, name)
values
(200,'B')
insert into @MyTable
(id, name)
values
(200,'B')
select id, row_number() over(partition by id order by id) as RowNum
from @MyTable