Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL list all rows where column A appears more than once but have distinct Column B values

I have two columns for example, I want to list all the rows where the items in ROW A appears more than once in Column A, but have distinct values in Column B. So far I have not figured out an answer

Column A     Column B
Apple         x
Banana        a
Orange        b
Orange        b
Banana        x
Avocado       d
like image 594
JimS Avatar asked Sep 13 '25 14:09

JimS


2 Answers

Try this query:

SELECT ColumnA
FROM table t
GROUP BY ColumnA
HAVING COUNT(DISTINCT ColumnB) >= 2;

An alternative HAVING clause that might be more efficient is:

HAVING MIN(ColumnB) <> MAX(ColumnB)
like image 68
Gordon Linoff Avatar answered Sep 16 '25 02:09

Gordon Linoff


Try this query:

SELECT ColumnA
FROM mytable 
GROUP BY ColumnA
HAVING COUNT(*) > 1 AND COUNT(DISTINCT ColumnB) = COUNT(*)
  • First predicate in HAVING clause is true if ColumnA value appears more than once.
  • Second predicate is true if all values in ColumnB are distinct within a ColumnA group.

SQL Fiddle Demo

like image 45
Giorgos Betsos Avatar answered Sep 16 '25 03:09

Giorgos Betsos