多个group by并使用mysql计算分组的行

时间:2015-05-09 07:15:14

标签: mysql

我在基于给定字段值进行分组来创建计数行时遇到问题。 例如:我有一个这样的数据结构:

+------+------------+
| id   | channel    |
+------+------------+
| 1    | "facebook" |
| 2    | "twitter"  |
| 3    | "facebook" |
| 2    | "facebook" |
| 4    | "twitter"  |
| 5    | "facebook" |
| 2    | "twitter"  |
| 1    | "facebook" |
| 2    | "twitter"  |
+------------+------+

我需要这个,我们已经知道了这个类别,它们将是静态的,即" facebook"和" 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链接:here is the fiddle

可能不是最优雅的答案,但设法提出:

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

如果有改进请,请回答或评论。

3 个答案:

答案 0 :(得分:2)

您好我认为您应该使用SUM(CASE声明)。这是如何锁定的:

SELECT id, SUM(CASE WHEN channel = 'facebook' THEN 1 ELSE 0 END) as facebook,
       SUM(CASE WHEN channel = 'twitter' THEN 1 ELSE 0 END) as twitter
FROM `data`
GROUP BY id
那个

Here is SQL Fiddle

答案 1 :(得分:0)

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

答案 2 :(得分:-1)

在mysql中的枢轴...... 看看这些:

基于你的小提琴(设置: - )的荣誉):

SELECT  
  id,  
  COUNT(if(channel = "facebook", 1, NULL)) AS facebook, 
  COUNT(if(channel = "twitter", 1, NULL)) AS twitter, 
  COUNT(if(channel = "isntagram", 1, NULL)) AS instagram, 
  COUNT(if(channel = "microsite", 1, NULL)) AS microsite, 
  COUNT(if(channel = "kiosk", 1, NULL)) AS kiosk, 
  COUNT(*) As Total
FROM data 
GROUP BY id;