我有两张桌子。 修理 - RepairID,EquipID,RepairDate
活动 - EventID,EquipID,ReturnDate,CustomerID
我正在尝试确定在维修完成之前最后一位客户是谁退回了设备。设备过去可能已经多次返回,但我只需要跟踪最后一个返回的客户。
最终结果将包括CustomerID,EquipID,ReturnDate,RepairDate
我的SQLFiddle用于示例DDL和查询: http://sqlfiddle.com/#!3/f2691/6/0
这将返回所有客户,而不仅仅是最后一个客户。
答案 0 :(得分:0)
这会回报你的期望吗?
选项1:
SELECT E.EquipID,
E.CustomerID,
max(E.ReturnDate) MAXRETURN
FROM Repair R
CROSS APPLY (
SELECT *,
row_number() OVER (
PARTITION BY EquipID ORDER BY ReturnDate DESC
) AS RN
FROM Event E
WHERE R.RepairDate > E.ReturnDate
AND E.EquipID = R.EquipID
) E
WHERE E.RN = 1
GROUP BY E.EquipID,
E.CustomerID
选项2:
SELECT E.EquipID,
E.CustomerID,
max(E.ReturnDate) MAXRETURN
FROM (
SELECT E.*,
row_number() OVER (
PARTITION BY E.EquipID ORDER BY E.ReturnDate DESC
) AS RN
FROM Event E
INNER JOIN Repair R
ON E.EquipID = R.EquipID
WHERE R.RepairDate > E.ReturnDate
) E
WHERE E.RN = 1
GROUP BY E.EquipID,
E.CustomerID