0
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

...但它很慢。

有没有更好的办法?

4

2 回答 2

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

这是一个小提琴:http ://sqlfiddle.com/#!3/4e1e3/4/0

于 2012-07-12T22:06:00.583 回答
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
于 2012-07-12T22:03:20.990 回答