我正在使用SQL Server中的失败指示器。
如果planned_receive_date
在12:00之前,则receive_date
必须在同一天。
如果planned_receive_date
在12:00之后,则receive_date可以在第二天之前。
我已经走到了这一步。我需要时间来决定它是在12.00之前还是之后。
但在计算失败时我只需要一天。并计算到小时
示例:
planned_receive_date 9/3/2014 6:10:00 AM
receive_date 9/4/2014 9:57:00 AM
它的计算失败(因为几小时)而且应该没问题(因为几天)。周末除外。我到目前为止得到了这个:
(case when (planned_receive_date > DATEADD(HH, 12, DATEDIFF(D, 0, planned_receive_date)))
THEN
(case
when datename(dw,planned_receive_date) = 'Friday'
then
(case
when receive_date > DATEADD(HH, 24, DATEDIFF(D, 0, (planned_receive_date+3)))
then 'FAILED'
ELSE 'OK' end)
when datename(dw,planned_receive_date) = 'Saturday'
then
(case when receive_date > DATEADD(HH, 24, DATEDIFF(D, 0, (planned_receive_date+2)))
then 'FAILED'
ELSE 'OK' end)
when datename(dw,planned_receive_date) = 'Sunday'
then
(case when receive_date > DATEADD(HH, 24, DATEDIFF(D, 0, (planned_receive_date+1)))
then 'FAILED'
ELSE 'OK' end)
else
(CASE
WHEN DATEADD(HH, 0, DATEDIFF(D, 0, receive_date)) = DATEADD(HH, 0, DATEDIFF(D, 0, planned_receive_date))
THEN 'OK'
ELSE
(case
when receive_date > DATEADD(HH, 24, DATEDIFF(D, 0, planned_receive_date))
then 'FAILED'
ELSE 'OK' end)
END)
end)
ELSE
(CASE
WHEN DATEADD(HH, 0, DATEDIFF(D, 0, receive_date)) > DATEADD(HH, 0, DATEDIFF(D, 0, planned_receive_date))
THEN 'FAILED'
ELSE 'OK'
END)
END)
as failed_indicator
答案 0 :(得分:1)
我认为这可以满足您的要求,希望您可以相对轻松地阅读我对每个部分的了解:
CASE WHEN receive_date <
DATEADD(day,DATEDIFF(day,0,planned_receive_date),
1+ --End of the planned day + ...
CASE
WHEN DATEPART(hour,planned_receive_date) < 12 THEN 0 --That day only
ELSE
CASE DATEPART(weekday,planned_receive_date)
WHEN DATEPART(weekday,'20141209') THEN 3 --Friday
WHEN DATEPART(weekday,'20141210') THEN 2 --Saturday
ELSE 1 --Next day
END
END
)
THEN 'OK'
ELSE 'FAILED'
END
那里的两个常数日期应该保持原样。我知道它最初可能看起来像是硬编码的东西只能在本周末使用,但实际上关于它们的唯一重要部分是我碰巧知道它们是(任意的)星期五和星期六。通过这样做,我不需要知道有效的DATEFIRST
设置或(在原始代码中)语言设置有效。