0

Here is the original table :

id type
1 A
1 A
1 B
2 A

Note that the content of type is VARCHAR and therefore can be anything.

I want to get an output like that :

id A B
1 2 1
2 1 NULL

How can I achieve that using mySQL ?

EDIT, here is what i tried so far :

SELECT u.id, i.type, count(*) as total
FROM intervention i,
     intervention_user iu,
     user u
WHERE i.id = iu.user_id
  AND iu.user_id = u.id
GROUP BY i.type, u.id;
dkst
  • 31
  • 3

1 Answers1

0

You can use conditional aggregation. I prefer 0 to NULL, so:

select id, sum(type = 'A') as a, sum(type = 'B') as b
from original
group by id;

If you want NULL values, one method uses NULLIF():

select id, nullif(sum(type = 'A'), 0) as a,
       nullif(sum(type = 'B'), 0) as b
from original
group by id;
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786