如何在我的 mysql 中使用 group_concat
how to use group_concat in my mysql
我有这个查询:
select IF(user_name IS NULL or user_name= '', distinct_id, user_name )
as user_info, event, count(event) as event_count
from mixpanel
where
(mixpanel.event = 'app_open' or
mixpanel.event = 'post_created' or
mixpanel.event = 'create_comment' or
mixpanel.event = 'class_opened' or
mixpanel.event = 'post_read')
AND
class_id = 'AKSJSDKSD'
group by event, user_name, distinct_id
order by user_name desc
它给了我以下结果:
+-----------+------------+--------+
| user_info | event | event_count |
+-----------+------------+--------+
| Ben Cho | up | 12 |
| Lee Mar | up | 21 |
| Lee Mar | side | 12 |
| Lee Mar | down | 16 |
| Al Gov | up | 14 |
| Al Gov | down | 13 |
| Al Gov | side | 13 |
+-----------+------------+--------+
我需要像这样聚合每个用户数据:
+-----------+------------+--------+
| user_info | up | down | side
+-----------+------------+--------+
| Ben Cho | 12 | 0 | 0 |
| Lee Mar | 21 | 16 | 12 |
| Al Gov | 14 | 13 | 13 |
+-----------+------------+--------+
我怎样才能在 mySql 上做到这一点?
谢谢!
据我所知,您只需要条件聚合。不需要 group_concat()
:
select (case when user_name IS NULL or user_name = '' then distinct_id else user_name
end) as user_info,
sum(mp.event = ('app_open')) as num_app_open,
sum(mp.event = ('post_created')) as num_post_created,
sum(mp.event = ('create_comment')) as num_create_comment
from mixpanel mp
where mp.event in ('app_open', 'post_created', 'create_comment') and
class_id = '-KtmM9EACwDTR98a_yU9'
group by user_info
order by user_info desc;
我有这个查询:
select IF(user_name IS NULL or user_name= '', distinct_id, user_name )
as user_info, event, count(event) as event_count
from mixpanel
where
(mixpanel.event = 'app_open' or
mixpanel.event = 'post_created' or
mixpanel.event = 'create_comment' or
mixpanel.event = 'class_opened' or
mixpanel.event = 'post_read')
AND
class_id = 'AKSJSDKSD'
group by event, user_name, distinct_id
order by user_name desc
它给了我以下结果:
+-----------+------------+--------+
| user_info | event | event_count |
+-----------+------------+--------+
| Ben Cho | up | 12 |
| Lee Mar | up | 21 |
| Lee Mar | side | 12 |
| Lee Mar | down | 16 |
| Al Gov | up | 14 |
| Al Gov | down | 13 |
| Al Gov | side | 13 |
+-----------+------------+--------+
我需要像这样聚合每个用户数据:
+-----------+------------+--------+
| user_info | up | down | side
+-----------+------------+--------+
| Ben Cho | 12 | 0 | 0 |
| Lee Mar | 21 | 16 | 12 |
| Al Gov | 14 | 13 | 13 |
+-----------+------------+--------+
我怎样才能在 mySql 上做到这一点?
谢谢!
据我所知,您只需要条件聚合。不需要 group_concat()
:
select (case when user_name IS NULL or user_name = '' then distinct_id else user_name
end) as user_info,
sum(mp.event = ('app_open')) as num_app_open,
sum(mp.event = ('post_created')) as num_post_created,
sum(mp.event = ('create_comment')) as num_create_comment
from mixpanel mp
where mp.event in ('app_open', 'post_created', 'create_comment') and
class_id = '-KtmM9EACwDTR98a_yU9'
group by user_info
order by user_info desc;