寻找T-SQL子查询的替代方案

时间:2012-07-12 21:59:39

标签: sql-server-2008 tsql subquery correlated-subquery

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

......但它很慢。

有更好的方法吗?

2 个答案:

答案 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

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

答案 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