简体   繁体   English

根据特定条件从SQL表中删除行

[英]Deleting rows from a SQL table based on specific criteria

I have a table that contains the following fields: issues to go (itg), customer number (ctm_nbr) and pub code (pub_cde). 我有一个包含以下字段的表:要处理的问题(itg),客户编号(ctm_nbr)和发布代码(pub_cde)。 The data looks like this 数据看起来像这样

12   010000024412  CTR
 6   010000024412  RTF
18   010000002325  CTR
 9   010000002325  RTF
 3   010000014789  CTR
 1   010000014789  RTF

I need to be able to delete all of the records where the RTF pub code and matching customer number is half of the issues to go (itg) in the CTR pub code for that matching customer. 我需要能够删除所有记录,其中RTF发布代码和匹配的客户编号是该匹配客户的CTR发布代码中要解决的问题(itg)的一半。 That way once I have all the records removed I would only have records like this remaining: 这样,一旦我删除了所有记录,我将只剩下这样的记录:

  3   010000014789  CTR
  1   010000014789  RTF

You might use something like: Delete all records for customer number x where the customer number has issues to go in CTR field that are twice the issues to go in the RTF field. 您可能使用类似以下内容的方法:删除客户编号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
                    )

You can use conditional aggregation: 您可以使用条件聚合:

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)

Fiddle: http://sqlfiddle.com/#!6/a7efe/1/0 小提琴: http ://sqlfiddle.com/#!6/a7efe/1/0

The reason I casted itg as decimal is to avoid the rounding issue that would otherwise occur due to your column being an interger data type (thanks to Laurence for pointing that out). 我将itg强制转换为十进制的原因是为了避免由于您的列是整数数据类型而导致的舍入问题(感谢Laurence指出了这一点)。

The tricky bit is getting both related records at one time: 棘手的一点是一次获取两个相关记录:

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 
    )
  );

Example SQL Fiddle SQL小提琴示例

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM