Jeff G
Jeff G

Reputation: 2175

SQL Query with Sum of Related Table

Have the following tables:

 Clients (ID, LastName)

 Orders (ID, ClientID)

 Payments (ID, OrderID, PaymentDate, Amount)

I need a SQL query that will return the list of client LastNames that have made payments after a given date that total at least some amount.

Example: Retrieve all clients who have made payments after 1/1/2011 that total at least $1,000.

I can get the clients who have made payments since a given date (1/1/2011) like this:

 SELECT Clients.LastName
 FROM   Clients
 WHERE  Clients.ID IN (SELECT Orders.ClientID
                       FROM   Orders
                       WHERE  Orders.ID IN (SELECT Payments.OrderID
                                            FROM   Payments
                                            WHERE  Payments.PaymentDate >= '2011-01-01'))

I can't figure out how to only get those clients where these payments add up to at least a given amount.

Upvotes: 3

Views: 2435

Answers (3)

Oleg Dok
Oleg Dok

Reputation: 21766

SELECT Clients.ID, Clients.LastName--, SUM(Amount) AS TotalPayments
FROM Clients
JOIN Orders ON Clients.ID = Orders.ClientId
JOIN Payments ON Payments.OrderId = Orders.Id
WHERE Payments.PaymentDate > '20110101'
GROUP BY Clients.ID, Clients.LastName
HAVING SUM(Amount) >= 1000

If you want to know an exact sum - uncomment the commented part in first line of query

Upvotes: 2

Clay Garrett
Clay Garrett

Reputation: 1023

I believe something like this should work:

Clients.LastName
FROM   Clients
WHERE  Clients.ID IN (SELECT Orders.ClientID
                   FROM   Orders
                   WHERE  Orders.ID IN (SELECT Payments.OrderID
                                        FROM   Payments
                                        WHERE  Payments.PaymentDate >= '2011-01-01' 
                                        GROUP BY Payments.OrderId 
                                        HAVING SUM(Payments.Amount) > 1000))

Upvotes: 1

Blorgbeard
Blorgbeard

Reputation: 103525

I think you can use something like this:

select c.ID, c.LastName
from Clients c
join Orders o on o.ClientId=c.Id
join Payments p on p.OrderId=o.Id
where p.PaymentDate >= '2011-01-01'
group by c.ID, c.LastName
having sum(p.PaymentAmount) > 1000

Upvotes: 6

Related Questions