Question

I need to query a table, in which the amount of a field should be equal to another, in the same table, for the same group.

This is my table:

ID  BUYER   CAR
1   1   Audi
2   1   Audi
3   1   BMW
4   1   BMW
5   2   Audi
6   2   Audi
7   2   BMW
8   2   BMW
9   2   BMW

I need to get if a buyer has bought the same amount of Audi than BMW, if not, those rows shouldn't be retrieved.

So, with this logic, the query should return all the rows for buyer 1 only , because he has bought 2 Audi and 2 BMW.

This will be the return table:

ID  BUYER   CAR
1   1   Audi
2   1   Audi
3   1   BMW
4   1   BMW

Hope you can help me.

This is the table:

http://sqlfiddle.com/#!3/853fa/3

Was it helpful?

Solution

Group by buyer and use the having clause to filter by BMW and Audi count. Then select all records of the buyers found.

select *
from mytable
where buyer in
(
  select buyer 
  from mytable
  group by buyer
  having 
    sum(case when car = 'BMW' then 1 end) =
    sum(case when car = 'Audi' then 1 end)
);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top