如何为包含多列的CustomerId显示最大OrderId?
我有一个包含以下列的表:
CustomerId, OrderId, Status, OrderType, CustomerType
具有相同客户ID的客户可能有许多订单ID(1,2,3 ..)我希望能够在sql视图中与其他客户一起显示最大订单ID。我怎么能实现这个目标呢?
示例数据:
CustomerId OrderId OrderType
145042 1 A
110204 1 C
145042 2 D
162438 1 B
110204 2 B
103603 1 C
115559 1 D
115559 2 A
110204 3 A
答案 0 :(得分:1)
select * from table_name
where orderid in
(select max(orderid) from table_name group by customerid)
答案 1 :(得分:1)
执行此操作的一种方法是使用not exists
:
select t.*
from table t
where not exists (select 1
from table t2
where t2.CustomerId = t.CustomerId and
t2.OrderId > t.OrderId
);
这就是说:"从t
获取客户的所有行,而客户没有更高的订单ID。"
答案 2 :(得分:1)
我使用公用表格式ROW_NUMBER
:
;With Ordered as (
select *,
ROW_NUMBER() OVER (PARTITION BY CustomerID
ORDER BY OrderId desc) as rn
from [Unnamed table from the question]
)
select * from Ordered where rn = 1