Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I see if there are multiple rows with an identical value in particular column?

Tags:

sql

sql-server

I'm looking for an efficient way to exclude rows from my SELECT statement WHERE more than one row is returned with an identical value for a certain column.

Specifically, I am selecting a bunch of accounts, but need to exclude accounts where more than one is found with the same SSN associated.

like image 806
BueKoW Avatar asked Jul 20 '11 14:07

BueKoW


People also ask

How to select the same values in two columns in Excel?

1 In the Select Same & Different Cells dialog box, do the following operations:#N#(1.) Click the first button to select... 2 Then click OK, and the same values both in column A and column B have been selected in column A. More ...

How to display duplicate row if there are identical rows?

In the adjacent blank cell, cell D2 in this case, please enter the below formula: 2. And then drag the fill handle down to the cells for applying this formula, now, you can see, if there are identical rows in this used range, it will display Duplicate row, see screenshot: 1.

How do I compare two columns in a table?

Click the first button to select the source column to be compared, then click the second button to select the column you are compared with; (2.) Choose Each row under the Based on section; (3.) Then select Same Values fromt he Find section;

How to compare two columns in Excel to find duplicate values?

Click button to execute the code, in the popped out box select Range 1 that you want to compare. 3. Click OK and go on selecting Range 2 that you will be compared with. 4. Then click OK, and the duplicate values both in column A and column C have been selected in column A.


2 Answers

this will return all SSNs with exactly 1 row

select ssn,count(*)
from SomeTable
group by ssn
having count(*) = 1

this will return all SSNs with more than 1 row

select ssn,count(*)
from SomeTable
group by ssn
having count(*) > 1

Your full query would be like this (will work on SQL Server 7 and up)

select a.* from account a
join(
select ssn
from SomeTable
group by ssn
having count(*) = 1) s on a.ssn = s.ssn
like image 91
SQLMenace Avatar answered Dec 14 '22 22:12

SQLMenace


For SQL 2005 or above you can try this:

WITH qry AS
(
    SELECT a.*,
        COUNT(*) OVER(PARTITION BY ssn) dup_count
      FROM accounts a
)
SELECT *
  FROM qry
 WHERE dup_count = 1

For SQL 2000 and 7:

SELECT a.*
  FROM accounts a INNER JOIN 
    (
        SELECT ssn
          FROM accounts b
            GROUP BY ssn 
            HAVING COUNT(1) = 1
    )  b ON a.ssn = b.ssn
like image 25
Chandu Avatar answered Dec 14 '22 23:12

Chandu