Question

I'm trying to get the date difference between two columns and then ultimately, get the average days grouped by the contractor field. I was able to get most of the SQL down but I can't seem to figure out how to get the date difference for multiple if scenarios.

Basically, if the original date column is null and the new date column is not, get the date difference between the new date and date ordered. Vice versa. If both original and new date are null, just set the date diff to null. It should look like below, without accounting for the grouped average days.

enter image description here

SQL below (didn't include avg function yet):

SELECT PT1.CONTRACTOR AS 'Contractor', PT1.date_order AS "date ordered", PT1.DATE_COMPLETED AS "original date", PT2.DATE_COMPLETED AS "new date",
  IF(PT1.DATE_COMPLETED = NULL AND PT2.DATE_COMPLETED IS NOT NULL, DATEDIFF(PT2.DATE_COMPLETED, PT1.DATE_ORDER), IF(PT2.DATE_COMPLETED = NULL AND PT1.DATE_COMPLETED IS NOT NULL, DATEDIFF(PT1.DATE_COMPLETED, PT1.DATE_ORDER), NULL)) AS "DATE DIFF"
FROM PTABLE1 PT1
  INNER JOIN PTABLE2 PT2
    ON PT1.ID = PT2.ID
WHERE PT2.STATUS = 'To_do' OR PT2.STATUS = 'Completed'
  AND PT2.COMPLETE = 'Yes'
 -- GROUP BY PT1.CONTRACTOR
Was it helpful?

Solution

COALESCE is your friend - it returns the first non-null value in a list, or NULL if they are all NULL.

So what you want is probably

datediff(coalesce(original_date, new_date), order_date)

If both are null, datediff will return null.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top