简体   繁体   中英

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".

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

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 .

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; and discard any customers where that count is greater than one. But that's rather off-topic.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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