Sql server 2012 SQL Server 2012查询混乱

Sql server 2012 SQL Server 2012查询混乱,sql-server-2012,Sql Server 2012,我是SQL的初学者,我似乎无法对这个问题提出正确的查询: 使用相关子查询为每个客户返回一行,表示客户最早的订单(日期最早的订单)。每行应包括以下三列:EmailAddress、OrderID和OrderDate 我从加入订单和客户表开始。EmailAddress是customers表中唯一需要的列 SELECT EmailAddress, OrderDate, orderID FROM Customers c JOIN orders o ON c.Custom

我是SQL的初学者,我似乎无法对这个问题提出正确的查询:

使用相关子查询为每个客户返回一行,表示客户最早的订单(日期最早的订单)。每行应包括以下三列:EmailAddress、OrderID和OrderDate

我从加入订单和客户表开始。EmailAddress是customers表中唯一需要的列

      SELECT EmailAddress, OrderDate, orderID
      FROM Customers c JOIN orders o
      ON c.CustomerID = o.CustomerID
使用
ROW\u NUMBER()
为每个客户获取唯一的ID,这些客户按
OrderDate
降序订购。最新日期为
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

您仍然可以使用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;

一个不那么复杂的答案:

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)