Conditional Agregation for numbered states

ghoulfx :

I'm having a hard time wrapping my head around a SQL Query. I'm thinking that somehow conditional agregation can be used, but here is my situation:

I have the following table:

+------------+----------+--------------+-------------+------------------+
| Email_Name | Email_Id | Subject_Line | Customer_Id | Interaction_Type |
+------------+----------+--------------+-------------+------------------+
| Email1     |        1 | Hello_1      |           1 | SENT             |
| Email2     |        1 | Hello_1      |           2 | SENT             |
| Email3     |        1 | Hello_1      |           3 | OPEN             |
| Email4     |        1 | Hello_1      |           4 | OPEN             |
| Email5     |        1 | Hello_1      |           5 | CLICK            |
| Email6     |        1 | Hello_1      |           6 | SENT             |
+------------+----------+--------------+-------------+------------------+

Usually, the input data is ordered by customer ID, for example a email sent to 100 people will show up a 100 times (per customer id). If 50 emails are opened, I will have an additional 50 lines of the email with OPEN state and so on.

What I want to do is aggregate the data so I have a single line for each Email ID followed by 3 columns OPEN/SENT/CLICK with numbers saying how many times it was sent/opened/clicked.

Can it be done? Using MySql. Thank you kindly.

Gordon Linoff :

Conditional aggregation:

select email_id, 
       sum(Interaction_Type = 'SENT') as num_sent,
       sum(Interaction_Type = 'OPEN') as num_open,
       sum(Interaction_Type = 'CLICK') as num_click
from t
group by email_id;

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=5565&siteId=1