简体   繁体   中英

Difference between two dates that are on different rows and columns?

My table schema looks like this..

Load_ID | StopType | Departure_Date | Arrival_Date

There are two stop types PK(Pickup) or DL(Delivery)

If the stop type is PK then the departure date exists and if the stop type is DL then the delivery date exists. For each departure and delivery couple the load id is the same. What complicates this for me is that they aren't always in rows right next to each other. What query should I use?

you could try something like that:

select Load_ID, max(Departure_Date), max(Arrival_Date)
from Table
group by Load_ID

this query will return every load with both dates, next step to calculate difference via DATEDIFF , something like:

select Load_ID, DATEDIFF(max(Arrival_Date), max(Departure_Date)) as diff
from Table
group by Load_ID

Hrm. I don't really understand the question but I'll try and be a mind reader:

    with myCte
as
(
SELECT 
Load_ID, Max(Depature_date) as DDate, max(Arrival_Date) as ADate
from myTable
group by Load_ID
)

select Load_ID, DateDiff(day,DDate, ADate) as DateDifference

I'll assume you can't ever have more than one of each type. If the values are otherwise nulls you could get away with just a simple min() without the case expression inside. Calculating differences is easy now that the data is together within a row. (It does sound like the design of your table isn't quite ideal though.)

select
    Load_ID,
    min(case when StopType = 'PK' then Departure_Date end) as Departure_Date),
    min(case when StopType = 'DL' then Arrival_Date) as Arrival_Date
from T
group by Load_ID

You can do this in one query:

SELECT
Load_ID, MAX(Depature_date) as departDate, MAX(Arrival_Date) as arriveDate, DateDiff(day,MAX(Depature_date),MAX(Arrival_Date)) as DateDiff 
FROM mailboxfilefilters 
GROUP BY Load_ID

This is assuming you want the difference interval between the 2 dates to be in days.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM