I have the following SQL query:
SELECT DISTINCT
username,
(CASE WHEN role_id = 1 THEN SUM(user_roles.hours) ELSE NULL END) AS `Admin`,
(CASE WHEN role_id = 2 THEN SUM(user_roles.hours) ELSE NULL END) AS `Subscriber`
FROM user_roles
LEFT JOIN users ON users.id = user_roles.user_id;
The purpose of this query is to display on each rows the usernames and for each username the number of hours for Admins, Subscribers and so on.
This query produces the following results:
username Admin Subscriber
abc 10 0
abc 0 5
def 0 7
def 4 0
Each username should have a unique value that falls either under Admin or Subscriber (no users can have both)
I would like the output to be instead:
username Admin Subscriber
abc 10 5
def 4 7
Where there are no columns that show zeros and to have only one row result per usernames.
I hope it's clear what I'm trying to accomplish here.
Thanks for any help