1

I have a people table, two of this table fields are id and country.

I want to find all records that have the same id and country, because id should be unique per country.

What would be the right way do do that?

for example, sample output should be:

+--------------+---------+
| id           | country |
+--------------+---------+
| 123          | AT      |
| 123          | AT      |
| 456          | GB      |
| 456          | GB      |
| 456          | GB      |
| 789          | AU      |
| 789          | AU      |
2
  • Please add sample data (tables) and desired output Commented Jan 23, 2019 at 15:03
  • @DDS done, added example output Commented Jan 23, 2019 at 15:15

3 Answers 3

1

Simple GROUP BY with HAVING clause will suffice:

SELECT id, country
FROM people
WHERE id <> "" AND id IS NOT NULL
GROUP BY id, country
HAVING COUNT(*) > 1
Sign up to request clarification or add additional context in comments.

8 Comments

this solution gives me also single fields..please see the example output that I added to the question
It will give you single fields, but those fields are repeated. In your example my query would return 123 and AT, 456 and GB, 789 and AU.
got you...you right, it would help if it was possible to exclude id != "" and id is not null, i only interested when id actually have a number
I get Empty set . and tried elect * from suppliers where id = "123" and country = "FR"; and found results of 2 records, so the query should find those :/ @Michał Turczyn
@JohnBigs Then replace people table with suppliers
|
0
    SELECT p1.* FROM people p1
    INNER JOIN people p2
    ON p1.id = p2.id AND p1.country = p2.country
    ORDERY BY p1.id

Comments

0

this may work

 with cte as (SELECT id -- extracts ID for countryes present more than 1 time
FROM people
GROUP BY id, country
HAVING COUNT(*) > 1)

select id, country -- adds repeated values
from people p join cte on p.id=cte.id

Comments

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.