简体   繁体   English

ORACLE SQL-删除计数> 1的所有记录

[英]ORACLE SQL - Delete any records with count > 1

I am collecting customers into a temp table who have a particular product, for this example will be called "Foobar". 我正在将具有特定产品的客户收集到临时表中,因为此示例将称为“ Foobar”。

CREATE TABLE  TEMP_CUSTOMERS AS
SELECT ROW_ID, CUSTOMER_ID
FROM PRODUCT prod
WHERE prod.NAME = 'Foobar'

Some customers may have multiple Foobars, so there count would be greater than 1 in the table for their given CUSTOMER_ID 一些客户可能有多个Foobars,因此对于他们给定的CUSTOMER_ID,表中的计数将大于1

My question is, how can I delete all customers who have more than one record in the table? 我的问题是,如何删除表中具有多个记录的所有客户?

I tried this 我试过了

DELETE FROM TEMP_CUSTOMERS
WHERE COUNT(CUSTOMER_ID) > 1

This did not work. 这没有用。

Since you want to delete all of the rows for those customers, you could do a correlated delete with a subquery that identifies those with more than one row: 由于要删除这些客户的所有行,因此可以使用子查询进行相关删除,该子查询标识具有多行的客户:

DELETE FROM TEMP_CUSTOMERS
WHERE CUSTOMER_ID IN (
  SELECT CUSTOMER_ID
  FROM TEMP_CUSTOMERS
  GROUP BY CUSTOMER_ID
  HAVING COUNT(*) > 1
);

SQL Fiddle demo . SQL Fiddle演示

It would still probably be simpler and more efficient to not insert those duplicates in the first place. 不首先插入那些重复项可能仍会更简单,更有效。 You could do an analytic count as part of your CTAS, maybe, in an inline view; 您可以在内联视图中作为CTAS的一部分进行分析计数。 and discard any customers where that count is greater than one. 并丢弃计数大于1的所有客户。 But that's rather off-topic. 但这是不合时宜的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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