1

I need to show the ID (which is unique in every case) and the name, which is sometimes different. In my code I only want to show the names IF they are unique.

I tried with both distinct and count(*)=1, nothing solves my problem.

SELECT DISTINCT id, name
FROM person
GROUP BY id, name
HAVING count(name) = 1;

The result is still showing the names multiple times

The Impaler
  • 45,731
  • 9
  • 39
  • 76
Ithil Maethor
  • 59
  • 1
  • 7

2 Answers2

2

If your DBMS supports it, you can use a window function:

SELECT id, name
FROM (
  SELECT id, name, COUNT(*) OVER(PARTITION BY name) AS NameCount -- get count of each name
  FROM person
) src
WHERE NameCount = 1

If not, you can do:

SELECT id, name
FROM person
WHERE name IN (
  SELECT name
  FROM person
  GROUP BY name
  HAVING COUNT(*) = 1 -- Only get names that occur once
)
ravioli
  • 3,749
  • 3
  • 14
  • 28
2

By "unique", I assume you mean names that only appear once. That is not what "distinct" means in SQL; the use of distinct is to remove duplicates (either for counting or in a result set).

If so:

SELECT MAX(id), name
FROM person
GROUP BY name
HAVING COUNT(*) = 1;
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786