0

I assume this was asked already once but I didn't find the right answer unfortunately.

I have multiple tables around customer data and all have the foreign key company_id. My goal is to have a list in which the first column gives me the company_id and the other columns aggregated values (e.g. COUNT) from other table. All grouped by the company_id

For example:

company_id | COUNT(products) | COUNT(purchases)

My approach was something like this but it didn't work out and I can't make up my mind of it (apart from using vlookups in excel)

SELECT pro.company_id, COUNT(*)
(SELECT pu.company_id, COUNT(*) FROM purchases pu GROUP BY pu.company_id) as 'COUNT(Purchases)'
FROM products pro
GROUP BY pro.company_id
3
  • Skip the GROUP BY in the subqeury, instead put a WHERE clause condition refrencing the pro table. Commented Mar 26, 2021 at 14:54
  • Tag the question with the database you are using. Commented Mar 26, 2021 at 14:55
  • @GordonLinoff Thank you! This was easier than expected... Unfortunately, I didn't understand the union_all approach you suggested me 😅 Hence, I'm happy that this works fine as well Commented Apr 6, 2021 at 17:53

2 Answers 2

1

I would suggest using union all and aggregation:

SELECT p.company_id, SUM(is_product), SUM(is_purchase)
FROM ((SELECT pr.company_id, 1 as is_product, 0 as is_purchase
       FROM products pro
      ) UNION ALL
      (SELECT pu.company_id, 0 as is_product, 1 as is_purchase
       FROM purchases pu
      )  pp      
GROUP BY p.company_id

Note that this keeps all products in either table, so the results can have 0 counts in one or the other columns.

Sign up to request clarification or add additional context in comments.

Comments

0

Aggregate each table and then join to customer:

SELECT com.company_id, "COUNT(Purchases)", "COUNT(Products)"
from companies as com
left join
 (
   SELECT company_id, COUNT(*) as "COUNT(Purchases)"
   FROM purchases 
   GROUP BY company_id
 ) as pu
on com.company_id = pu.company_id
left join
 (
   SELECT company_id, COUNT(*) as "COUNT(Products)"
   FROM products 
   GROUP BY company_id
 ) as pro

If there's no row for a customer this displays NULL, if you want to return 0 switch to coalesce("COUNT(Products)", 0)

3 Comments

Thank you! This works well for me :) I was wondering what would you do differently if you'd query aggregated values from the companies table and add the COUNT(Purchases) and COUNT(Products) to it?
I don't understand exactly what you try to do, but you can easily add a GROUP BY to the outer select and sum("COUNT(Purchases)")
Okay, let me try this again. It didn't work when I tried to add the GROUP BY to the other select statement. That's why I asked

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.