0

I tried referring to other questions; I've inferred that sub-queries cannot be used on aggregate functions, but I cannot solve this use case.

Tables:  
1. CustomerInfo(c_id,name)  
2. ProductInfo(p_id,price)  
3. ModelInfo(p_id,m_id,name)  
4. PurchaseRecords(c_id,m_id,quantity)

Required output:
List of customer names, with total amount purchased by each customer.

My flow of thought is that:
Link PurchaseRecords with ModelInfo to get p_id,
ModelInfo with ProductInfo to get the price,
Multiply price returned by quantity in PurchaseRecords for every specific customer,
which requires me to link CustomerInfo in the end to get the name.

I'm using Postgres. I could write a program for that in Java, but I find it hard to do it with SQL. So, what is the correct query here? Any pointers on how to think problems out are appreciated!

3
  • 2
    To make things easier to answer you really should build a schema, with sample data and an expected output based on that. Perhaps using sqlfiddle or a similar tool. Commented Dec 28, 2018 at 10:51
  • I did it on pgAdmin 4 with sample data; how do I share it here? Thanks! Commented Dec 28, 2018 at 11:09
  • You could use sqlfiddle. Don't forget to edit your question adding its link. :) Commented Dec 28, 2018 at 11:11

1 Answer 1

1
SELECT
  c.name as customer_name,
  sum(coalesce(p.price, 0) * coalesce(pr.quantity, 0)) as amount_purchased
from
  CustomerInfo c
  left join PurchaseRecords pr on c.c_id = pr.c_id
  left join ModelInfo mi on mi.m_id = pr.m_id
  left join ProductInfo p on p.p_id = mi.p_id
group by
  c.name
Sign up to request clarification or add additional context in comments.

Comments

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.