[英]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.