1

我有这种情况。我有一张OrdersOrderStatus.

OrderStatus

id | orderId | created

我需要检索Orders最后状态。我试过这个查询,我不知道它是否有效。我需要知道是否有更好的解决方案。

select Orders.id, OrderStatus.status from Orders
inner join OrderStatus on OrderStatus.id = 
    (select top 1 id from OrderStatus where orderId = Order.id order by created desc)
4

2 回答 2

2

您可以使用以下Row_Number功能:

WITH CTE AS
(
   SELECT Orders.id, OrderStatus.status,
      RN = ROW_NUMBER() OVER (
                        PARTITION BY OrderStatus.OrderId 
                        ORDER BY created DESC) 
   FROM Orders
   INNER JOIN OrderStatus ON  OrderStatus.OrderId = Orders.id
)
SELECT id, status
FROM CTE WHERE RN = 1

我使用了一个common-table-expression,因为它可以直接过滤并且它也非常易读。

于 2013-02-19T16:05:32.083 回答
2

相关子查询通常是坏消息(有时 SQL Server 可以优化它,有时它就像一个非常慢的循环)。也不确定为什么你认为你DISTINCT只需要最新状态时需要,除非你没有任何主键......

;WITH x AS 
(
  SELECT o.id, os.status, 
    rn = ROW_NUMBER() OVER (PARTITION BY os.orderId ORDER BY created DESC)
    FROM dbo.Orders AS o
    INNER JOIN dbo.OrderStatus AS os
    ON o.id = os.orderId
)
SELECT id, status
  FROM x
  WHERE rn = 1;
于 2013-02-19T16:05:37.367 回答