我的Sales.Customer
表包含以下列:
我的Sales.SalesOrder
表包含以下列:
有些客户在一段时间内已经下了多个订单。我编写了以下查询来检索每个客户下订单的最后日期:
SELECT c.CustomerID, c.FirstName, c.LastName,
-- correlated subquery goes here
AS LastOrderDate
FROM Sales.Customer AS c;
为什么我的子查询没有完成我的实际查询?我错过了什么或者它应该是不同的东西吗?
(SELECT MAX(o.OrderDate)
FROM Sales.SalesOrder AS o
WHERE o.CustomerID = c.CustomerID)
我考虑过是否可能会使我的解决方案过于复杂,所以这可能会起作用吗?
(SELECT MAX(c.OrderDate)
FROM Sales.Customer AS c)
答案 0 :(得分:0)
您应该可以将其重写为这样的CTE。
;WITH LastOrderDate AS
(
SELECT CustomerID,MAX(OrderDate) AS LastOrderDate
FROM Sales.SalesOrder
GROUP BY CustomerID
)
SELECT c.CustomerID, c.FirstName, c.LastName, LastOrderDate
AS LastOrderDate
FROM Sales.Customer AS c
LEFT JOIN LastOrderDate l
ON c.CustomerID = l.CustomerID;