You can use the below "technician"
First, run query # 1. It creates a query (query number 2), which must be run in order to get the result you need. Please continue to consider Moshi’s comments before heading “wild” with thousands of categories: o)
Request No. 1:
SELECT 'select UserID, ' + GROUP_CONCAT_UNQUOTED( 'sum(if(category = "' + STRING(category) + '", 1, 0)) as ' + STRING(category) ) + ' from YourTable group by UserID' FROM ( SELECT category FROM YourTable GROUP BY category )
The result will be as shown below - Request No. 2
SELECT UserID, SUM(IF(category = "A", 1, 0)) AS A, SUM(IF(category = "B", 1, 0)) AS B, SUM(IF(category = "C", 1, 0)) AS C FROM YourTable GROUP BY UserID
of course for three categories - you can do it manually, but for thousands it will definitely make a day for you!
The result of query # 2 will look as you expect:
UserID ABC 1 1 1 0 2 0 0 1 3 1 1 1
Mikhail Berlyant
source share