Skip to content
Advertisement

Aggregate SQL query across multiple tables by grouping

I want to group the record from the multiple tables.

Sample data:

What I have tried:

Desired Output:

How can I aggregate two tables which are not related and group by with Id and Name?

  1. Join and Aggregate Activity with Users
  • Learning Activity is the sum of (Videos, Text, Page and Image) as ActivityType
  • Chat is all the rows having the Chat as ActivityType
  1. Join and Aggregate LogTable with Users

Advertisement

Answer

You should aggregate before joining, this avoids getting a many-to-many-join which results in overcounting:

See fiddle

Simplifying the CASEs (COALESCE takes care of NULLs):

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement