如何在sql server中显示主键的最大日期

时间:2016-09-10 09:37:34

标签: sql sql-server tsql

with bookingdetails as (
    select  booking_master.booking_datetime as newdatetime, 
            booking_master.ETA as neweta 
    from booking_master where booking_ID='143'
)

上面的输出是:

newdatetime             neweta
2016-10-02 03:00:00.000 2016-10-05 03:00:00.000

比我运行:

with comparetrucklog as (
    select  truck_log.truck_id as bookedtruck, 
            truck_log.ETA as eta 
    from truck_log 
    where (select newdatetime from bookingdetails) between truck_log.pickupdate and truck_log.ETA 
        or (select neweta from bookingdetails) between truck_log.pickupdate and truck_log.ETA
)

在预订时,comparetrucklog的结果列37重复了两次,但我需要在eta中仅显示最大日期时间。

enter image description here

我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:0)

为什么简单的max()会正常工作?

 select bookedtruck, max(eta) from bookingmaster group by bookedtruck