42

I am trying to find rows that have duplicate values, but only based off of a select number of columns, not a single column or the entire row. For example, if my table looked like this:

ID     Address    State    Name
-------------------------------
0      7 Brown    NY       John
1      3 Red      WX       Jane
2      7 Brown    WX       Ted
3      7 Brown    NY       Fred

My question would be:

Find all ID's for rows where the row's Address and State field matched another row's Address and State field.

The answer to this query would be:

ID    Address    State    Name
------------------------------
0     7 Brown    NY       John
3     7 Brown    NY       Fred

Any Ideas?

Suggestions: How to select multiple columns values same rows from single table

1
  • Perhaps tag with "TSQL" ? Commented Apr 23, 2019 at 15:36

2 Answers 2

59

Try the following:

SELECT A.*
FROM YourTable A
INNER JOIN (SELECT Address, State
            FROM YourTable
            GROUP BY Address, State
            HAVING COUNT(*) > 1) B
ON A.Address = B.Address AND A.State = B.State
Sign up to request clarification or add additional context in comments.

3 Comments

ok, while these both work just fine. I think i will stick with this one. Thanks.
Better and simple way to handle this kind of scenario stackoverflow.com/questions/13807314/…
@himanshupareek66 I fail to see the difference. The reason for the join here we because op wanted the whole row where there were duplicates, not just address and state
4
select *
from #table1
where Addr + St in (select Addr + St as FullAddr
             from #table1
             group by Addr + St
             having count(Addr+St) > 1)

1 Comment

The string concatenation operator in SQL is || not +. But it would be better to use where (addr, st) in (select addr, st from ...) anyway instead of concatenating strings (which might have problems with some combinations of address and state)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.