Click here to Skip to main content
15,889,595 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi all

Please tell me how to delete records which repeated less than or equal 2 times.
below is the select query i wrote to get the data which repeated more then 2 times in my database table

SQL
SELECT count(*) as count, bill_no
FROM transaction_details
GROUP BY bill_no
HAVING COUNT(*) > 2
ORDER BY bill_no;
Posted
Comments
Rajesh waran 26-Feb-15 23:49pm    
Not Clear.Do you want to delete records which is repeated less than or equal to 2?
but your query returns repeated records greater than 2. Can you explain it clearly with sample data's?
Black_Rose 27-Feb-15 0:39am    
This is a query i wrote to get the records repeated more then 2 time.
i want to keep this records and delete other records which repeated <=2 times
Rajesh waran 27-Feb-15 2:23am    
Now i have updated my solution. Have a look

1 solution

Not Sure with my solution.If you want to delete records which is repeated less than or equal to 2,then try like this,
Edit:2
SQL
delete from transaction_detailswhere bill_no in (
select b.bill_no from transaction_details as a right join (
SELECT count(*) as count, bill_no
FROM transaction_details
GROUP BY bill_no
HAVING COUNT(*)<=2
) as b on a.bill_no=b.bill_no
);

Or if you want to delete records with count > 2, do like this
SQL
delete from transaction_detailswhere bill_no in (
select b.bill_no from transaction_details as a right join (
SELECT count(*) as count, bill_no
FROM transaction_details
GROUP BY bill_no
HAVING COUNT(*)>2
) as b on a.bill_no=b.bill_no
);
 
Share this answer
 
v3
Comments
Black_Rose 27-Feb-15 0:42am    
Ur first query giving below error

Msg 1033, Level 15, State 1, Line 8
The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP or FOR XML is also specified.

I want the first one..
Rajesh waran 27-Feb-15 2:20am    
Sorry Just remove ORDER BY Clause from both query.It works fine.Now updated. Have a look

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900