SQL - 与聚合混淆

时间:2010-12-14 22:08:21

标签: sql aggregate

我目前有这个查询:

select
  customers.emailaddress,
  MAX(orders.orderdate) as "last order"
from orders
join customers
  on orders.customerID = customers.customerID
group by customers.emailaddress

这给了我电子邮件和最后订单日期。使用'Orders'表,有一个名为'PaymentTotal'的字段,我如何根据MAX(orders.orderdate)返回的值得到这个? (即我试图获得每封电子邮件的最后订单金额)

1 个答案:

答案 0 :(得分:3)

select c.EmailAddress, om.MaxOrderDate, o.PaymentTotal
from (
    select CustomerID, MAX(orders.orderdate) as MaxOrderDate
    from orders 
    group by CustomerID
) om
inner join orders o on om.CustomerID = o.CustomerID
    and om.MaxOrderDate = o.orderdate
inner join customers c on o.customerID = c.customerID