我正在尝试获取两列之间的日期差异,然后最终获得按承包商字段分组的平均天数。我能够让大部分SQL失败,但我似乎无法弄清楚如何获得多个if方案的日期差异。
基本上,如果原始日期列为空且新日期列不为空,请获取新订购日期和日期之间的日期差异。反之亦然。如果原始日期和新日期均为空,则只需将日期差异设置为null。它应该如下所示,而不考虑分组的平均天数。
下面的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
答案 0 :(得分:2)
COALESCE是你的朋友 - 它返回列表中的第一个非空值,如果它们都是NULL,则返回NULL。
所以你想要的可能是
datediff(coalesce(original_date, new_date), order_date)
如果两者都为null,则datediff将返回null。