Skip to content
Advertisement

Find duplicate values in a field results in multiple rows of the same values

Suppose this table

I want to get all CODEs where SIZEPOS has the same value more than once…

So for the product

('194342-01', 10510, 5),
('194342-01', 10510, 7),
('194342-01', 10510, 9),
('194342-01', 10510, 11),
('194342-01', 10510, 13),
('194342-01', 10510, 15),
('194342-01', 10510, 5),
('194342-01', 10510, 19),

I would like to get '194342-01', 10510, 5 as SIZEPOS 5 appears twice. I achieved it with the following query

SELECT CODE, ITEID, COUNT(SIZEPOS) AS CNT
FROM @SUBSTITUTE
GROUP BY CODE, ITEID, SIZEPOS
HAVING COUNT(SIZEPOS) > 1;

but for some reason some of the returned rows appear twice, or even three times… What am I missing here?

Advertisement

Answer

I ended up using DISTINCT in my main query to avoid rows appearing more than once. So the query became like this:

SELECT DISTINCT CODE, ITEID, COUNT(SIZEPOS) AS CNT
FROM @SUBSTITUTE
GROUP BY CODE, ITEID, SIZEPOS
HAVING COUNT(SIZEPOS) > 1;

The rows that were appearing more than once, were rows that had different values with duplicates, so each row corresponded to every different duplicate value! This was easy but took me some time to figure out!

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement