I was having problems in creating counting rows by grouping based on a given field value. For example: I have a data structure like this:
+------+------------+
| id | channel |
+------+------------+
| 1 | "facebook" |
| 2 | "twitter" |
| 3 | "facebook" |
| 2 | "facebook" |
| 4 | "twitter" |
| 5 | "facebook" |
| 2 | "twitter" |
| 1 | "facebook" |
| 2 | "twitter" |
+------------+------+
And I need this, we already know the category, they will be static i.e."facebook" and "twitter":
+------+------------+------------+---------+
| id | Facebook | Twitter | Total |
+------+------------+------------+---------+
| 1 | 2 | 0 | 2 |
| 2 | 1 | 3 | 4 |
| 3 | 1 | 0 | 1 |
| 4 | 0 | 1 | 1 |
| 5 | 1 | 0 | 1 |
+------+------------+------------+---------+
sqlfiddle link: here is the fiddle
May not be the most elegant of answers but managed to come up with:
select user_id,user_name,
count(case when channel = "twitter" then channel end) Twitter,
count(case when channel = "facebook" then channel end) Facebook,
count(case when channel in ("twitter","facebook") then channel end) Total
from april
group by user_id order by Total desc
If there improvements please, do answer or comment.