Skip to content
Advertisement

MySQL result Group by two values

I need some help for a query to group some rows, I’m trying the whole day and find no solution and I’m sure it’s easy. Maybe some one can bring me light in the dark:

My Table:

I want only the result Bid=25 if I have Cid 11, 16 and value 33, 150

I tried

But in this case I get all possible Cid’s …

It seems I’m on a wood way.

Advertisement

Answer

Your query is tricky because you are looking for the presence of pairs of column values in a given group. One way to go here is to aggregate by Bid, Cid, and value, first, with the restriction that each record has a matching pair. Then subquery this by Bid and check that the count be 2, indicating that both pairs were present.

Demo

Since you are using SQL Server we can slightly refactor the above query to this:

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement