删除从包含Oracle中的having和group by子句的Select语句返回的行

时间:2013-07-24 11:18:12

标签: sql oracle select oracle11g having-clause

我有这个选择声明:

SELECT d.idcprefix,
         d.orgdept,
         d.idcseq,
         d.subcont, 
         d.actualcomp, 
         COUNT (*) AS "No Duplicates"
    FROM DCS_IDC, DCS_IDC z
   WHERE     D.IDCPREFIX = z.idcprefix
         AND z.orgdept = d.orgdept
         AND z.idcseq = d.idcseq
         and D.SUBCONT is not null
  HAVING COUNT (*) > 1
GROUP BY d.idcprefix,
         d.orgdept,
         d.idcseq,
         d.subcont,
         d.actualcomp
ORDER BY d.idcprefix,
         d.orgdept,
         d.idcseq,
         d.subcont,
         d.actualcomp

我希望删除从此语句中带回的行,任何想法?

删除FROM会给我一个ORA-01732: data manipulation operation not legal on this view错误,因为我相信,我正在比较两个表,尽管是同一个表。

我还尝试删除 tablename ,其中存在,但删除的行数远远超过我想要的行数。

“重复”基于Subcont。使用subcont字段将数据/应用程序插入到数据库/应用程序中的记录是空白的,所以现在我的记录是相同的,除了一个例如,在子下的A中,而在另一个中它是空白的:

idcprefix, subcont, orgdept and idcseq
1          A        ABC         1
1                   ABC         1
2          A        BCD         1
2                   BCD         1

查询显示所有子记录中的子记录与没有子记录的子记录重复,我需要删除具有子记录值的子记录。

非常感谢帮助!

2 个答案:

答案 0 :(得分:0)

假设(idcprefix,subcont,orgdept,idcseq)是唯一的,下面怎么样?

DELETE FROM DCS_IDC
WHERE (idcprefix, subcont, orgdept, idcseq) IN (
  WITH del AS (
  SELECT d.idcprefix,
     d.orgdept,
     d.idcseq,
     d.subcont, 
     d.actualcomp, 
     COUNT (*) AS "No Duplicates"
  FROM DCS_IDC, DCS_IDC z
  WHERE     D.IDCPREFIX = z.idcprefix
     AND z.orgdept = d.orgdept
     AND z.idcseq = d.idcseq
     and D.SUBCONT is not null
  HAVING COUNT (*) > 1
  GROUP BY d.idcprefix,
     d.orgdept,
     d.idcseq,
     d.subcont,
     d.actualcomp
  ORDER BY d.idcprefix,
     d.orgdept,
     d.idcseq,
     d.subcont,
     d.actualcomp
  )
 SELECT idcprefix, subcont, orgdept, idcseq FROM del
)

答案 1 :(得分:0)

怎么样:

BEGIN
  FOR aRow IN (SELECT d.idcprefix,
                      d.orgdept,
                      d.idcseq,
                      COUNT(*) AS DUP_COUNT
                 FROM DCS_IDC d
                 HAVING COUNT(*) > 1
                 GROUP BY d.idcprefix,
                          d.orgdept,
                          d.idcseq)
  LOOP
    DELETE FROM DCS_IDC
      WHERE IDCPREFIX = aRow.IDCPREFIX AND
            ORGDEPT = aRow.ORGDEPT AND
            IDCSEQ = aRow.IDCSEQ AND
            SUBCONT IS NOT NULL;
  END LOOP;
END;

无保证。使用风险由您自己承担。没有在动物身上测试过 - 你会成为第一个!

分享并享受。