Link to home
Start Free TrialLog in
Avatar of wasabi3689
wasabi3689Flag for United States of America

asked on

how to remove non-duplicated row

I have a person table, I want to remove all the entry with count=1

select grp, COUNT(*) as s from hpmg_dup_person
group by grp
order by s

Open in new window


how to do that?
Avatar of Jim Horn
Jim Horn
Flag of United States of America image

;with cte as (SELECT grp, COUNT(grp) as the_count FROM hpmg_dup_person GROUP BY grp) 
DELETE FROM cte WHERE the_count = 1

Open in new window


Deleting duplicates is covered here --> SQL Server Delete Duplicate Rows.  I'll have to add a blurb to this to cover deleting non-duplicates per your question.
Avatar of wasabi3689

ASKER

Msg 4403, Level 16, State 1, Line 2
Cannot update the view or function 'cte' because it contains aggregates, or a DISTINCT or GROUP BY clause, or PIVOT or UNPIVOT operator.
ASKER CERTIFIED SOLUTION
Avatar of Sharath S
Sharath S
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
--So effectively you wanted to to have records where you have more than 1 record per grp. In this case you can use row_number to delete the records.

--
CREATE TABLE hpmg_dup_person
(
	 grp INT
	,a INT
)
GO

INSERT INTO hpmg_dup_person
VALUES

(1,100),
(1,101),
(2,102),
(2,103),
(3,104),
(4,105),
(5,106),
(6,107)
GO

--

Open in new window



--SOLUTION 1

--


DELETE a
FROM (SELECT *, COUNT(*) OVER (PARTITION BY grp) cnt FROM hpmg_dup_person)a WHERE cnt = 1


--

Open in new window



--SOLUTION 2

--



DELETE b FROM
(	
	SELECT * FROM 
	(
		select grp, COUNT(*) as s from hpmg_dup_person
		group by grp
	)u 
	WHERE s = 1
	
)k INNER JOIN hpmg_dup_person b ON k.grp = b.grp


--

Open in new window


The above code will delete records where count per grp is 1. !!

O/p

/*------------------------


DELETE b
FROM
(      
      SELECT * FROM
      (
            select grp, COUNT(*) as s from hpmg_dup_person
            group by grp
      )u
      WHERE s = 1
      
)k INNER JOIN hpmg_dup_person b ON k.grp = b.grp
------------------------*/

(4 row(s) affected)
Hi wasabi3689,
A feedback will be appreciated.

Regards
Pawan