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
......但它很慢。
有更好的方法吗?
答案 0 :(得分:3)
您可以使用具有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
答案 1 :(得分: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