请准备以下表格:
Clients (ID, LastName)
Orders (ID, ClientID)
Payments (ID, OrderID, PaymentDate, Amount)
我需要一个SQL查询,它会返回在给定日期之后付款的客户LastNames列表,该日期总计至少有一些金额。
示例:检索2011年1月1日之后至少总计1,000美元的所有客户。
我可以获得自指定日期(2011年1月1日)以来付款的客户:
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'))
我无法弄清楚如何只获得这些付款累计至少一定金额的客户。
答案 0 :(得分:5)
我认为你可以使用这样的东西:
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
答案 1 :(得分:2)
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
如果您想知道确切的总和 - 取消注释第一行查询中的注释部分
答案 2 :(得分:1)
我相信这样的事情应该有效:
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))