robertsfd
Technical User
- Apr 18, 2003
- 40
I have the following two tables that track vendors and purchases made from vendors (one-to-many relationship):
Vendor(VendorID, VendorName)
Purchase(PurchaseID, Date, Amount, VendorID)
I want to list all vendors that have total purchases greater than the average total of purchases considering all vendors.
I know how to do this using a series of queries, but have not been able to combine it all into one query. Is this possible? I was unable to resolve this question based on prior postings I found.
Here are the four queries that I created to arrive at my deasired result, but I can't figure out how to get them all into one query.
Query 1 - list all unique VendorIDs in Purchase table:
SELECT DISTINCT Purchase.VendorID
FROM Purchase;
Query 2 - count the number of records in query 1 recordset:
SELECT Count(*)
FROM Query1;
Query 3 - sum the amount for all purchases:
SELECT Sum(Purchase.Amount)
FROM Purchase;
Query 4 - list the vendor names that have total purchases in the Purchase table greater than the average total purchases (Query 3 divided by Query 2):
SELECT Vendor.VendorName
FROM Vendor, Purchase
WHERE Vendor.VendorID=Purchase.VendorID
GROUP BY Vendor.VendorName
HAVING Sum(Purchase.Amount) >
(SELECT Query3.Expr1000 / Query2.Expr1000
FROM Query3, Query2);
Vendor(VendorID, VendorName)
Purchase(PurchaseID, Date, Amount, VendorID)
I want to list all vendors that have total purchases greater than the average total of purchases considering all vendors.
I know how to do this using a series of queries, but have not been able to combine it all into one query. Is this possible? I was unable to resolve this question based on prior postings I found.
Here are the four queries that I created to arrive at my deasired result, but I can't figure out how to get them all into one query.
Query 1 - list all unique VendorIDs in Purchase table:
SELECT DISTINCT Purchase.VendorID
FROM Purchase;
Query 2 - count the number of records in query 1 recordset:
SELECT Count(*)
FROM Query1;
Query 3 - sum the amount for all purchases:
SELECT Sum(Purchase.Amount)
FROM Purchase;
Query 4 - list the vendor names that have total purchases in the Purchase table greater than the average total purchases (Query 3 divided by Query 2):
SELECT Vendor.VendorName
FROM Vendor, Purchase
WHERE Vendor.VendorID=Purchase.VendorID
GROUP BY Vendor.VendorName
HAVING Sum(Purchase.Amount) >
(SELECT Query3.Expr1000 / Query2.Expr1000
FROM Query3, Query2);