SQL选择最新记录

时间:2013-08-29 15:53:16

标签: sql sql-server-2008

我正在尝试根据该记录的最新状态从订单表中选择一组记录。状态保存在另一个名为orderStatus的表中。我的表格更复杂,但这是一个基本的例子

表格 - 订单:

orderID

表 - orderStatus:

 orderStatusID
 orderID
 orderStatusCode
 dateTime

订单可以有很多状态记录,我只想获得具有我所查询的最新statusCode的订单。问题是我得到了很多重复。这是一个基本的例子。

select orders.orderID
from   orders inner join orderStatus on orders.orderID = orderStatus.orderID
where  orderStatusCode = 'PENDING'

我尝试过内部查询,从dateTime排序的orderStatus表中选择前1位。但我仍然看到同样的重复。有人能指出我如何做到这一点的正确方向吗?

编辑:SQL Server 2008

5 个答案:

答案 0 :(得分:2)

一个简单的LEFT JOIN来检查订单上是否存在新的状态应该可以正常执行;

SELECT o.* 
FROM orders o
JOIN orderStatus os
  ON o.orderID = os.orderID
LEFT JOIN orderStatus os2
  ON o.orderID = os2.orderID 
 AND os.dateTime < os2.dateTime
WHERE os.orderStatusCode = 'PENDING' AND os2.dateTime IS NULL;

答案 1 :(得分:0)

select DISTINCT orders.orderID
from   orders inner join orderStatus on orders.orderID = orderStatus.orderID
where  orderStatusCode = 'PENDING'

作为替代方案,您可以使用GROUP BY

select orders.orderID
from   orders inner join orderStatus on orders.orderID = orderStatus.orderID
where  orderStatusCode = 'PENDING'
GROUP BY orders.orderID

答案 2 :(得分:0)

select Distinct orders.orderID
from   orders inner join orderStatus on orders.orderID = orderStatus.orderID
where  orderStatusCode = 'PENDING'

答案 3 :(得分:0)

尝试使用这样的子选择:

Select
    o.*
FROM
    Order o inner join OrderStatus os on o.order_id = os.order_id
Where
    os.orderstatus_id in (SELECT max([orderstatus_id]) FROM [OrderStatus]  group by [order_id])
    And os.staus = 'pending'

答案 4 :(得分:0)

尝试使用日期时间的子查询?

 select orders.orderID
 from   orders inner join orderStatus on orders.orderID = orderStatus.orderID
 where  orderStatusCode = 'PENDING' AND (dateTime)=((SELECT MAX(dateTime) From orders 
 as orders2 Where orders= orders2))