|
|
|
Valued Member
      
Group: General Forum Members
Last Login: Tuesday, February 19, 2013 7:15 AM
Points: 68,
Visits: 181
|
|
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.
|
|
|
|
|
SSC Veteran
      
Group: General Forum Members
Last Login: Monday, October 01, 2012 3:30 PM
Points: 292,
Visits: 1,028
|
|
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?
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:
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
Regards,
goodguy
Experience is a bad teacher whose exams precede its lessons
|
|
|
|