我需要从订单表中获取所有先前的订单历史记录(最后一个)。问题是客户没有customerId
或唯一值。因此,我们获取信息的唯一方法是通过客户电话号码,客户地址,客户名称一起。我编写了以下查询来提取单个订单号的数据,但我需要知道如何使用此查询来提取10,000个客户记录。请帮忙!
SELECT TOP 1
O1.*
FROM
Orders AS O1
INNER JOIN
Orders AS O2 ON O1.CustAddress = O2.CustAddress
AND O1.CustName = O2.CustName
AND O1.CustPhone = O2.CustPhone
AND O1.OrderDate < O2.OrderDate
WHERE
O1.OrderId = '12345'
ORDER BY
O1.OrderDate DESC
答案 0 :(得分:2)
您可以使用ROW_NUMBER
和CTE:
WITH CTE AS
(
SELECT O1.*, RN = ROW_NUMBER () OVER (
PARTITION BY CustAddress, CustName, CustPhone
ORDER BY OrderDate DESC )
FROM Orders AS O1
WHERE O1.OrderId = '12345'
)
SELECT * FROM CTE WHERE RN = 1
每个CustAddress, CustName, CustPhone
- 组返回一行,最新的。