Account
=======
int AccountId PK
Order
=====
int OrderId PK
int AccountId FK
DateTime Date
int Status
对于每个帐户,我想知道状态为1(成功(的最新订单,否则是状态为0(不成功(的最新订单。 日期不是唯一的。
我已经在这样的视图中使用相关的子查询...
SELECT
a.AccountId,
(SELECT TOP 1
o.orderId
FROM
tbl_order o
WHERE
o.Accountid = a.AccountId
AND
o.Status IN (0, 1)
ORDER BY
o.Status DESC, o.Date DESC
) AS OrderId
FROM
tbl_account a
。但它很慢。
有没有更好的方法?
您可以使用
具有ROW_NUMBER
函数的 CTE:
WITH cte AS(
SELECT a.AccountId, o.OrderId, o.Date, o.Status
, RN = ROW_NUMBER()OVER(Partition By a.AccountId ORDER BY o.Status DESC, o.Date DESC)
FROM Account a
LEFT OUTER JOIN [Order] o ON a.AccountId = o.AccountId
)
SELECT AccountId, OrderId
FROM cte
WHERE RN = 1
这里有一个小提琴:http://sqlfiddle.com/#!3/4e1e3/4/0
试试这个:
SELECT
a.AccountId,
o.OrderId
FROM
tbl_account a OUTER APPLY
(
SELECT TOP 1 o.orderId
FROM tbl_order o
WHERE o.Accountid = a.AccountId
AND o.Status IN (0, 1)
ORDER BY o.Status DESC, o.Date DESC
) AS o