2017-12-27 2 views
0

내가이 쿼리가 :내 MySQL의에서 GROUP_CONCAT을 사용하는 방법을

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에서 수행 할 수 있습니까?

감사합니다.

+0

이것은'group_concat'을 사용하면 얻을 수 없습니다. 내가 이해할 때 당신은 피벗 조작을하고 있습니다. MySQL에서 자동으로 수행 할 수있는 방법이 있는지 모르겠습니다. 설명서도 읽을 수 있습니다 (그리고 알아 내기 위해). –

+0

나는 할 것이다. 빠른 응답을 주셔서 감사합니다 @ JonathanLeffler –

답변

0

내가 알 수있는 것부터 조건부 집계 만 있으면됩니다. 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; 
+0

바로 그 자리에! 고맙습니다! 이것은 내가 필요로했던 정확하게 것이었다! !! 신속한 답변에 다시 한 번 감사드립니다. 고맙 @ Gordon Linoff –

관련 문제