获取所有用户的第一次和最后一次发货以及到达日期

azi*_*z_h 5 sql sql-server greatest-n-per-group window-functions

我有船运公司的表格。

这些列是(国民 ID、装运日期、到达日期 ..)

问题是:如何获取每个用户的第一次发货日期和到达日期以及最后一次发货日期和到达日期

这是示例数据:

国民身份证 发货日期 到达日期
115 2020-10-08 2021-03-18
115 2023-02-08 1990年1月1日
115 2021-08-11 2021-08-20

我使用这个 QUERY 但它不起作用

select NationalID,
    min(shippmetdate) as first_shippment,
    min(arrivalDate) as arrival_first,
    max(shippmetdate) as last_shippment,
    max(arrivalDate)as arrival_last
from (
    select NationalID, shippmetdate, arrivalDate,
    ROW_NUMBER() over (partition by NationalID order by shippmetdate) as seq1, 
    ROW_NUMBER() over (partition by NationalID order by arrivalDate) as seq2 
    from shippment
) t 
group by NationalID
Run Code Online (Sandbox Code Playgroud)

输出是:

国民身份证 首次发货 首先到达 最后发货 最后抵达
115 2020-10-08 1990年1月1日 2023-02-08 2021-08-20

但我想要的输出像

国民身份证 首次发货 首先到达 最后发货 最后抵达
115 2020-10-08 2021-03-18 2023-02-08 1990年1月1日

实际上我想获取第一个发货的行,然后我将返回同一行的到达日期

我尝试使用最大值和最小值作为日期,但输出不匹配。

GMB*_*GMB 2

min我们只需使用和即可获得第一个和最后一个发货日期max

至于相应的到达日期,通过枚举每个用户的记录,然后聚合,您就走在正确的轨道上。您需要在外部查询中使用条件聚合;此外,还应调整顺序:两者都应为order by发货日期,但方向不同。

所以:

select NationalID,
    min(shipmentDate) as firstShipmentDate,
    max(case when seq1 = 1 then arrivalDate  end) as firstShipmentArrivalDate,
    max(shipmentDate) as lastShipmentDate,
    max(case when seq2 = 1 then arrivalDate  end) as lastShipmentArrivalDate
from (
    select s.*,
        row_number() over (partition by NationalID order by shipmentDate     ) as seq1, 
        row_number() over (partition by NationalID order by shipmentDate desc) as seq2 
    from shipment s
) s
group by NationalID
Run Code Online (Sandbox Code Playgroud)
国民身份证 首次装运日期 首次发货到达日期 最后发货日期 最后发货到达日期
115 2020-10-08 2021-03-18 2023-02-08 1990年1月1日

小提琴