Mysql GROUP BY列值

时间:2015-03-14 11:23:04

标签: mysql sql

我有一张桌子

+---------+----------+------------+---------------------+
| user_id | campaign | event_type | date                |
+---------+----------+------------+---------------------+
|       1 | MobiKwik | install    | 2015-03-14 09:56:33 |
|       2 | MobiKwik | install    | 2015-03-14 09:56:33 |
|       3 | Micromax | click      | 2015-03-14 09:56:33 |
|       4 | Quickr   | click      | 2015-03-14 09:56:33 |
|       5 | Quickr   | install    | 2015-03-14 09:56:33 |
|       6 | MobiKwik | click      | 2015-03-14 09:56:33 |
|       7 | Amazon   | install    | 2015-03-14 09:56:33 |
|       8 | MobiKwik | click      | 2015-03-14 09:56:33 |
|       1 | MobiKwik | install    | 2015-03-14 10:49:32 |
|       2 | MobiKwik | install    | 2015-03-14 10:49:32 |
|       3 | Micromax | click      | 2015-03-14 10:49:32 |
|       4 | Quickr   | click      | 2015-03-14 10:49:32 |
|       5 | Quickr   | install    | 2015-03-14 10:49:32 |
|       6 | MobiKwik | click      | 2015-03-14 10:49:32 |
|       7 | Amazon   | install    | 2015-03-14 10:49:32 |
|       8 | MobiKwik | click      | 2015-03-14 10:49:32 |
+---------+----------+------------+---------------------+

我想编写一个查询,按以下方式对结果进行分组,

Campaign InstallCount ClickCount
Amazon      2           0
Mobikwik    4           4
micromax    0           2
and so on.

我该如何撰写此类查询?

这是我试过的!!

select * from tablename group by campaign,even_type;

2 个答案:

答案 0 :(得分:2)

在MySQL中你可以做到

select campaign, 
       sum(even_type = 'install') as InstallCount,
       sum(even_type = 'click') as ClickCount
from tablename 
group by campaign

和ANSI SQL标准

select campaign, 
       sum(case when even_type = 'install' then 1 else 0 end) as InstallCount,
       sum(case when even_type = 'click' then 1 else 0 end) as ClickCount
from tablename 
group by campaign

答案 1 :(得分:0)

如果广告系列中的项目超过5个,最好这样做:

SET SESSION group_concat_max_len = 1000000;

SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
    CONCAT(
      'sum(case when tablename_.event_type = ''',
      event_type,
      ''' then 1 else 0 end)',
      event_type
    )
   )INTO @sql
FROM tablename_; 


SET @sql=CONCAT('SELECT campaign, ',@sql,' FROM tablename_ GROUP BY tablename_.campaign');



PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

代码库来自juergen d。