例如,我有一个包含值的简单表:
|Code|Value|
|x1 |5 |
|x2 |-5 |
|x3 |-5 |
|x4 |5 |
|x5 |5 |我需要删除之和等于0的行。也就是说,对于这个例子,我想删除代码为x1和x2、x3和x4或x1和x2、x3和x5的行--这在我的情况下并不重要。
听起来很简单,但我做不到。
我甚至不知道如何选择我想要删除的项目。
我试着像这样把桌子连在一起:
SELECT
t1.Code AS Code1,
t2.Code AS Code2
FROM TableX AS t1
JOIN TableX As t2
ON t1.Code <> t2.Code
AND t1.Value + t2.Value = 0
ORDER BY t1.Code结果:
|Code1|Code2
|x1 |x2
|x1 |x3
|x2 |x1
|x2 |x4
|x2 |x5
|x3 |x1
|x3 |x4
|x3 |x5
|x4 |x2
|x4 |x3
|x5 |x2
|x5 |x3但我不知道下一步该怎么办。
我并不懒惰--我尝试了不同的变体--使用GROUP和MIN,使用ROW_NUMBER(),但不幸的是,我无法理解如何选择要删除的行,并保留其他行?
发布于 2016-06-24 13:53:01
这似乎包括在内,我相信:
declare @t table (Code varchar(20) not null, Value int not null)
insert into @t(Code,Value) values
('x1',5 ),
('x2',-5 ),
('x3',-5 ),
('x4',5 ),
('x5',5 )
;With Ordered as (
select
Code,
Value,
ROW_NUMBER() OVER (PARTITION BY Value ORDER BY Code) rn
from
@t
), Pairs as (
select
o1.Code c1,
o2.Code c2
from
Ordered o1
inner join
Ordered o2
on
o1.Value = -o2.Value and
o1.rn = o2.rn
where
o1.Value > 0
)
delete from t from @t t where exists (
select * from Pairs p where p.c1 = t.Code or
p.c2 = t.Code)
select * from @t结果:
Code Value
-------------------- -----------
x5 5这将决定根据每一行的Value值,为每一行提供唯一的行号。然后,我们根据寻找行号相等但值相反的行对行。
如果您想了解select * from Ordered或select * from Pairs是如何工作的,那么它可能对delete或delete有指导意义。
https://stackoverflow.com/questions/38014849
复制相似问题