Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count of data from one column into multiple columns with MySQL?

I am having trouble understanding how to split and count different activities into separate columns. This is the beginning table:

+------------+---------+
| CustomerID |Activity |
+------------+---------+
|          1 | Click   |
|          1 | View    |
|          1 | Inquiry |
|          2 | Click   |
|          2 | View    |
|          3 | Click   |
|          3 | Click   |
+------------+---------+

I'd like to be able to transform it to this:

+------------+------+-------+---------+
| CustomerID | View | Click | Inquiry |
+------------+------+-------+---------+
|          1 |    1 |     1 |       1 |
|          2 |    1 |     1 |       0 |
|          3 |    0 |     2 |       0 |
+------------+------+-------+---------+
like image 775
J Hsia Avatar asked Sep 09 '16 04:09

J Hsia


People also ask

How do I count values in a column in MySQL?

MySQL COUNT(*) with GROUP BY Clause It returns the total number of values residing in each group. For instance, if you want to check each user's number separately, you have to define the column 'User' with the GROUP BY clause while counting records for each user with COUNT(*). >> SELECT User, COUNT(*) FROM data.

Can we use count without GROUP BY?

Using COUNT, without GROUP BY clause will return a total count of a number of rows present in the table. Adding GROUP BY, we can COUNT total occurrences for each unique value present in the column.


1 Answers

You can use case statement and sum like,

select 
    `CustomerID`,
    sum(case when `Activity` = 'View' then 1 else 0 end) `View`,
    sum(case when `Activity` = 'Click' then 1 else 0 end) `Click`,
    sum(case when `Activity` = 'Inquiry' then 1 else 0 end) `Inquiry`
from `tbl`
group by `CustomerID`
order by `CustomerID`

The output is

CustomerID  View    Click   Inquiry
1             1     1       1
2             1     1       0
3             0     2       0
like image 112
Praveen Avatar answered Oct 12 '22 21:10

Praveen