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

时间:2014-08-24 19:22:54

标签: sql sql-server-2008

我有一个包含以下字段的表:要去的问题(itg),客户编号(ctm_nbr)和pub代码(pub_cde)。数据看起来像这样

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

我需要能够删除所有记录,其中RTF酒吧代码和匹配的客户编号是该匹配客户的CTR pub代码中的问题的一半(itg)。这样一旦我删除了所有记录,我只会留下这样的记录:

  3   010000014789  CTR
  1   010000014789  RTF

4 个答案:

答案 0 :(得分:1)

您可以使用以下内容:删除客户编号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
                    )

答案 1 :(得分:1)

您可以使用条件聚合:

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指出这一点)。

答案 2 :(得分:1)

棘手的一点是同时获得两个相关记录:

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

答案 3 :(得分:1)

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))
相关问题