2
ID    OrderId  status
    1  12       1
    2  13       1
    3  14       2
    4  12       3
    5  15       1
    6  14       1

大家好,

尝试为上面的表构建 sql 查询以获得如下结果:

   OrderId  status
         12       3
         13       1
         14       1
         15       1

我想要具有最新状态码的唯一 orderid

我试过这个查询

Select Distinct OrderID 
from OrdersStatusHistory 
order by Status desc

获取记录但重复 orderid

Select OrderID, Status 
from Orders_Status_History 
order by Status desc

但我收到一个错误:

如果指定了 SELECT DISTINCT,则 ORDER BY 项目必须出现在选择列表中。

4

4 回答 4

2
select OrdersStatusHistory.* from OrdersStatusHistory
JOIN
 (select OrderId, max(id) maxId 
      from OrdersStatusHistory 
      group by OrderId) t1
 on OrdersStatusHistory.Id=t1.maxId
 order by OrdersStatusHistory.OrderId

SQLFiddle 演示

或者如果您需要为OrdeId

select OrderId,max(status)
from OrdersStatusHistory
group by OrderID
order by OrderId
于 2013-04-26T08:19:23.107 回答
1

你想要的结果错了吗?14出现两次,但最新状态为2

WITH CTE AS
(
   SELECT RN = ROW_NUMBER()OVER(PARTITION BY OrderId ORDER BY ID DESC) , OrderId, status
   FROM dbo.Orders
)
SELECT  OrderId, status FROM CTE
WHERE RN = 1

演示

ORDERID STATUS
12          3
13          1
14          1  
15          1
于 2013-04-26T08:23:03.090 回答
0

你必须试试这个:

Select DISTINCT OrderID, Status from Orders_Status_History
于 2014-01-09T08:31:14.103 回答
0

试试这个查询。

Select orderid
,status 
from orders_status_history
where rowid in (Select max(rowid) 
from orders_status_history
group by orderid) order by order_id
于 2013-04-26T09:04:22.590 回答