我正在尝试添加行号来复制记录。
declare @tbl table
(col1 varchar(10),col2 varchar(10) )
insert into @tbl values ('a1','b1')
insert into @tbl values('a1','b1')
insert into @tbl values ('a1','b2')
insert into @tbl values('a2','b2')
insert into @tbl values('a2','b2')
insert into @tbl values('a2','b2')
insert into @tbl values('a3','b3')
insert into @tbl values('a3','b3')
select col1,col2,ROW_NUMBER() OVER(ORDER BY col1,col2 ) AS id from @tbl
以下是预期结果
declare @tbl1 table
(col1 varchar(10),col2 varchar(10),id int )
insert into @tbl1 values ('a1','b1',1)
insert into @tbl1 values('a1','b1',2)
insert into @tbl1 values ('a1','b2',1)
insert into @tbl1 values('a2','b2',1)
insert into @tbl1 values('a2','b2',2)
insert into @tbl1 values('a2','b2',3)
insert into @tbl1 values('a3','b3',1)
insert into @tbl1 values('a3','b3',2)
select * from @tbl1
答案 0 :(得分:3)
试试这个你需要使用分区
SELECT col1,
col2,
Row_number()
OVER(
partition BY col1, col2
ORDER BY col1, col2 ) AS id
FROM @tbl
答案 1 :(得分:2)
row_number
将始终为窗口中的每一行赋予不同的值。如果要检测重复项,则需要使用rank
代替:
SELECT col1, col2,
RANK() OVER (PARTITION BY col1, col2 ORDER BY col1, col2) AS id
FROM @tbl
或仅查询重复项:
SELECT col1, col2
FROM (SELECT col1, col2,
RANK() OVER (PARTITION BY col1, col2 ORDER BY col1, col2) AS id
FROM @tbl) t
WHERE id > 1