我是SQL的初学者,我似乎无法对这个问题提出正确的查询:
使用相关子查询为每个客户返回一行,表示客户最早的订单(具有最早日期的订单)。每行应包括以下三列:EmailAddress,OrderID和OrderDate。
我开始加入订单和客户表。 EmailAddress是customers表中唯一需要的列。
SELECT EmailAddress, OrderDate, orderID
FROM Customers c JOIN orders o
ON c.CustomerID = o.CustomerID
答案 0 :(得分:5)
一个不那么复杂的答案:
SELECT EmailAddress, OrderID, OrderDate AS OldestOrder
FROM Customers AS C
JOIN Orders AS O1
ON C.CustomerID = O1.CustomerID
WHERE O1.OrderDate =
(SELECT MIN(OrderDate)
FROM Orders AS O2
WHERE C.CustomerID = O2.CustomerID)
答案 1 :(得分:1)
使用ROW_NUMBER()
为按OrderDate
降序排序的每位客户获取唯一ID。最新日期为RNO=1
。现在在外部查询中进行过滤。
SELECT EmailAddress, OrderDate, orderID
FROM
(
SELECT ROW_NUMBER() OVER(PARTITION BY c.CustomerID ORDER BY OrderDate DESC)RNO,
EmailAddress, OrderDate, orderID
FROM Customers c JOIN orders o
ON c.CustomerID = o.CustomerID
)TAB
WHERE RNO=1
答案 2 :(得分:1)
您仍然可以使用HAVING子句和IN运算符来实现此特定问题的相同结果
代码:
SELECT DISTINCT EmailAddress, OrderID, OrderDate
FROM Customers
JOIN orders
ON Customers.CustomerID = Orders.CustomerID
GROUP BY EmailAddress, OrderID, OrderDate
HAVING OrderID IN (1,2,4,5,6,7,8)
ORDER BY EmailAddress ASC;