问题
I have a table of events that stores the events for users and I want to get the number of two specific events for each user.
An example table is called "events" and it has 2 columns
user_id VARCHAR(50)
event_name VARCHAR(50)
The user_ids are all unique and the event names can be things like login, sent_message, liked_post
How do I, for example, query for the total messages sent per user AND the number of liked_posts per user?
回答1:
This is the pattern of query you can use:
select user_id,
sent_message_count=sum(case when event_name = 'Sent Message' then 1 else 0 end),
liked_post_count=sum(case when event_name = 'Liked Post' then 1 else 0 end),
from events
group by user_id
Now, you just need to make sure the when
part of each case
statement fits the criteria you need. The pattern itself - summing a bunch of 1's where the criteria fits, is really the key to achieving the result you're after.
回答2:
SELECT user_id,
SUM(IF(event_name = 'sent_message', 1, 0)) AS sent_message,
SUM(IF(event_name = 'liked_posts', 1, 0)) AS liked_posts
FROM `events`
GROUP BY user_id
来源:https://stackoverflow.com/questions/35944845/how-do-i-count-multiple-columns-of-events-for-users