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 |
+------------+------+-------+---------+
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With