0

I know someone on here already asked the similar questions. However, most of them still want to return the first row or last row if multiple rows have the same attributes. For my case, I want to simply discard the rows which have the same specific attributes.

For example, I have a toy dataset like this:

gender age  name
  f     20   zoe
  f     20   natalia
  m     39   tom
  f     20   erika 
  m     37   eric
  m     37   shane
  f     22   jenn

I only want to distinct on gender and age, then discard all rows if those two attributes, which returns:

gender age  name
  m     39   tom
  f     22   jenn

3 Answers 3

2

You could use the window (analytic) variant of count to find the rows that have a just one occurance of the gender/age combination:

SELECT gender, age, name
FROM   (SELECT gender, age, name, COUNT(*) OVER (PARTITION BY gender, age) AS cnt
        FROM   mytable) t
WHERE  cnt = 1
Sign up to request clarification or add additional context in comments.

Comments

1

Use the HAVING clause in a CTE.

;WITH DistinctGenderAges AS
(
    SELECT gender
        ,age
    FROM YourTable
    GROUP BY gender
        ,age
    HAVING COUNT(*) = 1
)
SELECT yt.gender, yt.age, yt.name
FROM DistinctGenderAges dga
INNER JOIN YourTable yt ON dga.gender = yt.gender AND dga.age = yt.age 

2 Comments

Name is not part of the distinct
@Paparazzi my answer has been updated and now works as OP intended.
-1

No matter what, you have to tell the database which value to pick for name. If you don't care an easy solution is to group:

SELECT gender, age, MIN(name) as name FROM mytable GROUP BY gender, age HAVING COUNT(*)=1

You can use any valid aggregate for name, but you have to pick something.

3 Comments

This doesn't filter out the records with multiples.
Right, the wording didn't make sense to me. I will amend.
I don't have a testing platform at the moment but when all rows with multiple corresponding records are eliminated by the HAVING COUNT(*)=1, this is exactly what the result will be.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.