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.
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 ...
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.
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;
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With