SQL Server 2012 查询混乱
SQL Server 2012 Query Confusion
我是 SQL 的初学者,我似乎无法针对这个问题提出正确的查询:
使用相关子查询 return 每个客户一行,代表客户最早的订单(日期最早的订单)。每行应包括以下三列:EmailAddress、OrderID 和 OrderDate。
我从加入订单和客户开始 table。 EmailAddress 是客户 table.
唯一需要的列
SELECT EmailAddress, OrderDate, orderID
FROM Customers c JOIN orders o
ON c.CustomerID = o.CustomerID
使用 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
对于这个特定问题,您仍然可以使用 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)
我是 SQL 的初学者,我似乎无法针对这个问题提出正确的查询:
使用相关子查询 return 每个客户一行,代表客户最早的订单(日期最早的订单)。每行应包括以下三列:EmailAddress、OrderID 和 OrderDate。
我从加入订单和客户开始 table。 EmailAddress 是客户 table.
唯一需要的列 SELECT EmailAddress, OrderDate, orderID
FROM Customers c JOIN orders o
ON c.CustomerID = o.CustomerID
使用 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
对于这个特定问题,您仍然可以使用 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)