March 7, 2008 at 5:48 pm
Hi All,
I'm hitting a wall(don't know why). I have four tables. Table one contains user information, Table 2 contains actual orders, Table 3 contains future orders and Table 4 contains all invoices that the user has accumulated. Table 2 ; Table 3; Table 4 will have different data having UserId as a common field. I'll need to do an outer join to get the total count for a user my resultset needs to look something like this:
Username Orders Placed Orders Paid Invoices
John Doe 20 30 24
Jane Doe 5 25 10
John Smith 0 10 0
All tables have different data but I need to get the counts for all tables for each user. What is the best way to get this done?
Thank You in advanced.
March 8, 2008 at 12:57 am
[Quote]I have 4 tables. Table1 contains user information, Table2 contains actual orders, Table3 contains future orders and Table4 contains all invoices that the user has accumulated. Table 2, Table3 and Table4 will have different data having UserId as a common field. I'll need to do an outer join to get the total count for a user my resultset needs to look something like this:
Username Orders Placed Orders Paid Invoices
John Doe 20 30 24
Jane Doe 5 25 10
John Smith 0 10 0
All tables have different data but I need to get the counts for all tables for each user. What is the best way to get this done?[/Quote]
First of all, it is poor DB design to have separate tables for for current and future orders; better to have them together and keep a Flag column to distinguish between them.
Table4 "contains all invoices that the user has accumulated", but your resultset column is headed "Paid Invoices", so I assume you have a flag for flagging an invoice once it is paid.
Use LEFT OUTER JOIN in your query as follows:
[Code]SELECT a.CUSTID, b.ORDERSCOUNT, c.PENDINGCOUNT, d.PAIDCONT
FROM TABLE1 a
LEFT OUTER JOIN
(
SELECT CUSTID, COUNT(ORDER) as ORDERSCOUNT
FROM TABLE2
GROUP BY CUSTID
) b
ON a.CUSTID = b.CUSTID
LEFT OUTER JOIN
(
SELECT CUSTID, COUNT(ORDER) as PENDINGCOUNT
FROM TABLE2
GROUP BY CUSTID
) c
ON a.CUSTID = c.CUSTID
LEFT OUTER JOIN
(
SELECT CUSTID, COUNT(ORDER) as PAIDCOUNT
FROM TABLE2
WHERE PAIDFLAG = 1
GROUP BY CUSTID
) d
ON a.CUSTID = d.CUSTID[/Code]
Viewing 2 posts - 1 through 1 (of 1 total)
You must be logged in to reply to this topic. Login to reply