I have a table with some data like
id group_id f1 f2 f3
1 1 a b
2 1 c
3 2 a c
How can i retrieve one row with group_id and count of rows for each field satisfying some textual condition?
Like that:
MY_MAGIC_SELECT(`f1`='a',`f3`='c');
must return
group_id f1 f2 f3
1 1 0 0
2 1 0 1
Using a sequence of
SUM(CASE...)aggregate functions to represent each of your conditions should do it. TheCASEreturns a 0 or 1 if the condition is matched, and theSUM()adds the result. TheGROUP BYis applied on thegroup_id.Specifically for MySQL, you don’t need the
CASEsince the boolean expressionf1 = 'a'will itself return a 1 or 0. So you can simplify it to the example below. This is not portable to any RDBMS, however.Here is a quick demonstration on SQLfiddle.com