I currently have a table where I am tracking a bunch of events tracking the origin of such events. I am currently creating a report by company summarizing all the different origins of such events.
The table seems as follows
-------------------------------------
| company_id | source | date |
-------------------------------------
| 156012 | facebook | 2016-08-22|
| 156012 | twitter | 2016-08-22|
| 156012 | facebook | 2016-08-12|
| 160781 | twitter | 2016-07-20|
| 160781 | twitter | 2016-07-20|
I have omitted several fields and that's just sample data. I am gathering a report that counts the events by source to each company. I would like my report to look something like this
| company_id | facebook | twitter |
------------------------------------
| 156012 | 2 | 1 |
| 150781 | 2 | 0 |
Currently I am doing it this way
select company_id,
sum(if(track.source = 'facebook', 1,0)) as facebook,
sum(if(track.source = 'twitter', 1,0)) as twitter,
from event_tracks as track
group by franchise_id
order by total_clicks desc limit 10;
I Would like to know if there's a better way to do this as the source field might take a wide range of values, so the report won't be a nice fit for larger data.