Search code examples
sqlhive

SQL function to download rows with specific values only


I have duplicate IDs with different activities. To return all the IDs, but remove duplicates, and to return three new columns called email, phone call and appointment containing true if activity is (email(for email columns), phone call(for phone column), appointment(for appointment columns)), otherwise false.

What I have

ID Activity
101 Email
101 Appointment
102 Campaign
103 Phone call
104 Appointment
SELECT id,

MAX(CASE WHEN activity='Phone Call' THEN TRUE ELSE FALSE END) AS PhoneCall, 
MAX(CASE WHEN activity='Appointment' THEN TRUE ELSE FALSE END) AS Appointment,
MAX(CASE WHEN activity='Email' THEN TRUE ELSE FALSE END) AS Email

| 104 | Campaign |

What I want

ID Email Appointment Phone call
101 True True False
102 False False False
103 False False Ture
104 False Ture False

Solution

  • This should be what you are looking for

    SELECT id, MAX(CASE WHEN activity='Email' THEN 'True' ELSE 'False' END) AS Email, MAX(CASE WHEN activity='Appointment' THEN 'True' ELSE 'False' END) AS Appointment, MAX(CASE WHEN activity='Phone Call' THEN 'True' ELSE 'False' END) AS 'Phone Call' FROM {your_table_name} GROUP BY id;