I am trying to select rows from a table that have duplicates in one column but also restrict the rows based on another column. It does not seem to be working correctly.
select Id,Terms from QueryData
where Track = 'Y' and Active = 'Y'
group by Id,Terms
having count(Terms) > 1
If I remove the where
it works fine but I need to restrict it to these rows only.
ID Terms Track Active
100 paper Y Y
200 paper Y Y
100 juice Y Y
400 orange N N
1000 apple Y N
Ideally the query should return the first 2 rows.
Don't exactly get what you're doing. You use
count(Terms)
inhaving
howeverTerms
is in yourselect
clause. It means that for each recordscount(Terms)
will be 1. Probably you have to excludeTerms
fromselect
list. Honestly i reproduced your table and query and it doesn't work.Probably this is what you're looking for(?):
This will return all duplicated terms meeting the criteria:
http://sqlfiddle.com/#!3/18a57/2
If you want all the details for these terms, you can join to this result.
http://sqlfiddle.com/#!3/18a57/5
Demo on SQLFiddle
Data:
Results: