加入 and/or 个子查询或排名函数

Joins and/or Sub queries or Ranking functions

我有一个table如下:

Order_ID Ship_num Item_code Qty_to_pick Qty_picked Pick_date
1111 1 1 3000 0 Null
1111 1 2 2995 1965 2021-05-12
1111 2 1 3000 3000 2021-06-24
1111 2 2 1030 0 Null
1111 3 2 1030 1030 2021-08-23
2222 1 3 270 62 2021-03-18
2222 1 4 432 0 Null
2222 2 3 208 0 Null
2222 2 4 432 200 2021-05-21
2222 3 3 208 208 2021-08-23
2222 3 4 232 200 2021-08-25

由此table, 我只想显示具有最新 ship_num 信息的行,而不是最新的 pick_date 信息(我被引导到这样的问题,需要 return 具有最新条目的行时间,我不是在寻找那个)为了一个订单,即我想要它如下

Order_ID Ship_num Item_code Qty_to_pick Qty_picked Pick_date
1111 3 2 1030 1030 2021-08-23
2222 3 3 208 208 2021-08-23
2222 3 4 232 200 2021-08-25

我尝试了以下查询,

select order_id, max(ship_num), item_code, qty_to_pick, qty_picked, pick_date
from table1
group by order_id, item_code, qty_to_pick, qty_picked, pick_date

如有任何帮助,我们将不胜感激。

提前致谢。

您可以使用 DENSE_RANK() 获取它。

查询

;with cte as (
    select rnk = dense_rank()
       over (Partition by order_id order by ship_num desc)
        , *
    from table_name
)
Select *
from cte
Where rnk =1;

使用 max(ship_num) 是个好主意,但您应该使用解析版本(带有 OVER 子句)。

select *
from
(
  select t.*, max(ship_num) over (partition by order_id) as orders_max_ship_num
  from table1 t1
) with_max
where ship_num = orders_max_ship_num
order by order_id, item_code;