Fer*_*rna 5 sql sql-server rows duplicates
我在批量插入脚本中犯了一个错误,所以现在我有不同colX的"重复"行.我需要删除这些重复的行,但我无法弄清楚如何.更确切地说,我有这个:
col1 | col2 | col3 | colX
----+----------------------
0 | 1 | 2 | a
0 | 1 | 2 | b
0 | 1 | 2 | c
0 | 1 | 2 | a
3 | 4 | 5 | x
3 | 4 | 5 | y
3 | 4 | 5 | x
3 | 4 | 5 | z
Run Code Online (Sandbox Code Playgroud)
我想保留每个(row,colX)的第一次出现:
col1 | col2 | col3 | colX
----+----------------------
0 | 1 | 2 | a
3 | 4 | 5 | x
Run Code Online (Sandbox Code Playgroud)
谢谢您的回复 :)
Mic*_*uen 10
尝试使用Sql Server的CTE最简单的方法:http://www.sqlfiddle.com/#!3/2d386 /2
数据:
CREATE TABLE tbl
([col1] int, [col2] int, [col3] int, [colX] varchar(1));
INSERT INTO tbl
([col1], [col2], [col3], [colX])
VALUES
(0, 1, 2, 'a'),
(0, 1, 2, 'b'),
(0, 1, 2, 'c'),
(0, 1, 2, 'a'),
(3, 4, 5, 'x'),
(3, 4, 5, 'y'),
(3, 4, 5, 'x'),
(3, 4, 5, 'z');
Run Code Online (Sandbox Code Playgroud)
解:
select * from tbl;
with a as
(
select row_number() over(partition by col1 order by col2, col3, colX) as rn
from tbl
)
delete from a where rn > 1;
select * from tbl;
Run Code Online (Sandbox Code Playgroud)
输出:
| COL1 | COL2 | COL3 | COLX |
-----------------------------
| 0 | 1 | 2 | a |
| 0 | 1 | 2 | b |
| 0 | 1 | 2 | c |
| 0 | 1 | 2 | a |
| 3 | 4 | 5 | x |
| 3 | 4 | 5 | y |
| 3 | 4 | 5 | x |
| 3 | 4 | 5 | z |
| COL1 | COL2 | COL3 | COLX |
-----------------------------
| 0 | 1 | 2 | a |
| 3 | 4 | 5 | x |
Run Code Online (Sandbox Code Playgroud)
或许这个:http://www.sqlfiddle.com/#!3/af826/1
数据:
CREATE TABLE tbl
([col1] int, [col2] int, [col3] int, [colX] varchar(1));
INSERT INTO tbl
([col1], [col2], [col3], [colX])
VALUES
(0, 1, 2, 'a'),
(0, 1, 2, 'b'),
(0, 1, 2, 'c'),
(0, 1, 2, 'a'),
(0, 1, 3, 'a'),
(3, 4, 5, 'x'),
(3, 4, 5, 'y'),
(3, 4, 5, 'x'),
(3, 4, 5, 'z');
Run Code Online (Sandbox Code Playgroud)
解:
select * from tbl;
with a as
(
select row_number() over(partition by col1, col2, col3 order by colX) as rn
from tbl
)
delete from a where rn > 1;
select * from tbl;
Run Code Online (Sandbox Code Playgroud)
输出:
| COL1 | COL2 | COL3 | COLX |
-----------------------------
| 0 | 1 | 2 | a |
| 0 | 1 | 2 | b |
| 0 | 1 | 2 | c |
| 0 | 1 | 2 | a |
| 0 | 1 | 3 | a |
| 3 | 4 | 5 | x |
| 3 | 4 | 5 | y |
| 3 | 4 | 5 | x |
| 3 | 4 | 5 | z |
| COL1 | COL2 | COL3 | COLX |
-----------------------------
| 0 | 1 | 2 | a |
| 0 | 1 | 3 | a |
| 3 | 4 | 5 | x |
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7885 次 |
| 最近记录: |