Question

I have a table like that has two attributes a and b. Now, there's a lot of data going through that stuff and I'd like to select all records where one value for a has more than 1 different value of b.

For example, from the following example table

   a    b
---------
   1    1
   1    1
   2    1
   2    2
   3    1
   4    1
   4    5
   4    1

I'd like to select

   a   b
--------
   2   1
   2   2
   4   1
   4   5

Or if not otherwise possible just 2 and 4 (as two result rows), so I can get more specific data in a second query.

I've tried working with GROUP BY and HAVING and also some constructs with subqueries, but nothing came close to the result I want. I really don't want to fetch all the data and crunch through manually.

It's probably something really simple, but I just cant get to it, so how would one solve this?

Was it helpful?

Solution

For a single table access (that returns all values of b for a specific value of a on the same line), try:

select a, group_concat(distinct b)
from yourtable
group by a
having count(distinct b) > 1

To return separate rows for each combination of a and b, try:

select distinct yt1.a, yt1.b
from yourtable yt1
join yourtable yt2 on yt1.a = yt2.a and yt1.b <> yt2.b

Exists variant:

select distinct a, b
from yourtable yt1
where exists
(select 1
 from yourtable yt2
 where yt1.a = yt2.a and yt1.b <> yt2.b)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top