Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

SQL question 2

Status
Not open for further replies.

dbadmin

Programmer
Jan 3, 2003
147
US
Hi,

I have a customer table with related tables (invoice, products etc). All these related tables have customer_id column as Foreign key. I need a query which will give me counts of invoices, products etc corresponding to each customer id for example like this

cust_id count(inv) count(prod)
100 10 40
101 2 10
102 22 25

I tried to join these tables and group by customer_id, but I am not getting the correct answer. How could I do this?

dbadmin
 
Try the following:

Code:
select c.cust_id,i.inv,p.prod
from customer c,
  (select cust_id,count(*) inv from invoice group by cust_id) i,
  (select cust_id,count(*) prod from product group by cust_id) p
where c.cust_id = i.cust_id
and c.cust_id = p.cust_id
 
You might need to use outer joins to pick up rows where there are no invoices and/or poducts for a customer.

Another possibility:

Code:
select c.customer_id, 
       count(distinct p.product_id),
       count(distinct i.invoice_id)
from customer c, invoice i, product p
where c.customer_id = p.customer_id(+)
and   c.customer_id = i.customer_id(+)
group by c.customer_id
 
Hi,

Thank you. I got what I was looking for. I have to thank both of you Dagon and dsancez2.

dbadmin
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top