[英]Deleting rows from a SQL table based on specific criteria
我有一个包含以下字段的表:要处理的问题(itg),客户编号(ctm_nbr)和发布代码(pub_cde)。 数据看起来像这样
12 010000024412 CTR
6 010000024412 RTF
18 010000002325 CTR
9 010000002325 RTF
3 010000014789 CTR
1 010000014789 RTF
我需要能够删除所有记录,其中RTF发布代码和匹配的客户编号是该匹配客户的CTR发布代码中要解决的问题(itg)的一半。 这样,一旦我删除了所有记录,我将只剩下这样的记录:
3 010000014789 CTR
1 010000014789 RTF
您可能使用类似以下内容的方法:删除客户编号x的所有记录,其中客户编号在CTR字段中有待处理的问题是在RTF字段中要处理的问题的两倍。
Delete
from --table--
where ctm_nbr in (select t2.ctm_nbr
from --table-- t2 join --table-- t3
ON (t2.ctm_nbr = t3.ctm_nbr)
where t2.pub_cde="CTR"
and t3.pub_cde="RTF"
and t2.itg = 2*t3.itg
)
您可以使用条件聚合:
delete from tbl
where ctm_nbr in(
select ctm_nbr
from tbl
group by ctm_nbr
having max(case when pub_cde = 'CTR' then cast(itg as decimal) end) /
max(case when pub_cde = 'RTF' then cast(itg as decimal) end) = 2)
小提琴: http ://sqlfiddle.com/#!6/a7efe/1/0
我将itg强制转换为十进制的原因是为了避免由于您的列是整数数据类型而导致的舍入问题(感谢Laurence指出了这一点)。
棘手的一点是一次获取两个相关记录:
delete
a1
from
a a1
where (
a1.pub_cde = 'RTF' and
exists (
select 'x'
from a a2
where a2.ctm_nbr = a1.ctm_nbr and
a2.pub_cde = 'CTR' and
a2.itg = 2 * a1.itg
)
) or (
a1.pub_cde = 'CTR' and
exists (
select 'x'
from a a2
where a2.ctm_nbr = a1.ctm_nbr and
a2.pub_cde = 'RTF' and
a2.itg * 2 = a1.itg
)
);
DELETE t1
FROM a t1
INNER JOIN a t2
ON t1.ctm_nbr = t2.ctm_nbr
WHERE
((t1.pub_cde = 'CTR') AND
(t2.pub_cde = 'RTF') AND
(2*t2.itg = t1.itg))
OR
((t2.pub_cde = 'CTR') AND
(t1.pub_cde = 'RTF') AND
(2*t1.itg = t2.itg))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.