获取按下两个可能的发货日期分组的订单行

时间:2019-04-08 11:00:10

标签: sql sql-server

我正在尝试在sql中弄清楚如何为接下来的两个可能的shippingDate选择所有订单行

订单行

    ID  Name       ShipmentDate
    1   Product 1    2019-04-10
    2   Product 1    2019-04-12
    3   Product 2    2019-04-12
    4   Product 1    2019-04-14

所需结果

    ID  Name       ShipmentDate
    1   Product 1    2019-04-10
    2   Product 1    2019-04-12
    3   Product 2    2019-04-12

1 个答案:

答案 0 :(得分:1)

一种方法使用dense_rank()

select ol.*
from (select ol.*,
             dense_rank() over (order by shipmentdate desc) as seqnum
      from orderlines ol
     ) ol
where seqnum <= 2;

或者,您可以在where子句中使用过滤:

select ol.*
from orderlines ol
where ol.shipmentdate >= (select distinct ol2.shipmentdate
                          from orderlines ol2
                          order by shipmentdate desc
                          offset 1 fetch first 1 row only
                         );