我试图获得两列之间的日期差异,然后最终获得按承包商字段分组的平均天数。我能够获取大部分 SQL,但我似乎无法弄清楚如何获取多个 if 场景的日期差异。
基本上,如果原始日期列为空而新日期列不是,则获取新日期和订购日期之间的日期差。反之亦然。如果原始日期和新日期都为空,只需将日期差异设置为空。它应该如下所示,不考虑分组的平均天数。
下面的 SQL(还没有包含 avg 函数):
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