数据库
首页 > 数据库> > 使用MySQL从一列到多列的数据计数?

使用MySQL从一列到多列的数据计数?

作者:互联网

我无法理解如何将不同的活动拆分和计算到不同的列中.这是开始表:

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

我希望能够将其转换为:

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

解决方法:

您可以使用案例陈述和总和,

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`

输出是

CustomerID  View    Click   Inquiry
1             1     1       1
2             1     1       0
3             0     2       0

标签:mysql,multiple-columns,table-splitting
来源: https://codeday.me/bug/20190608/1199183.html