I have generated the following table from SQL database:
First_User Second_User Count
User1 NULL 427
User3 NULL 69
User2 NULL 499
User1 User1 1
User4 User2 48
User5 User2 13
I want to create this table from the above table:
User Count
User1 429
User2 560
User3 69
User4 48
User5 13
Match first two column values and add the third column. I am aware to do it in python but how can I do it in SQL.
In pandas, it can be done using:
df = df.groupby(['User1', 'User2'])['Count'].sum().reset_index()
Thanks in advance.
2
Answers
This can be done using
UNION ALL
to combine both columns into a single column, then applyGROUP BY
and the aggregate functionSUM()
to get the expected output:Result :
Demo here
This actually requires a double aggregation union query.
Demo
Each half of the union aggregates by either the first or second user to get the sum of the counts (as a user might appear more than once). The outer query then aggregates by user to find the totals.