【发布时间】:2019-09-22 15:17:04
【问题描述】:
使用案例陈述解决了业务需求。 case 语句在多个日期属性中是相同的。我知道 case 语句一次只对单个属性起作用,并使用动态 sql 使其重复,但我们不想使用动态 sql。 有没有办法简化 case 语句,使其至少看起来重复且更易于理解。有什么想法吗?
CASE
WHEN Status IN ('Denied','Partial Approval') and NotificationDate <> '1900-01-01' AND NotificationDate < Requestdate THEN 'Error'
WHEN Status IN ('Denied','Partial Approval') and NotificationDate >= RequestDate THEN
CASE
when Type in ('Non-Urgent Preservice','Non-Urgent Concurrent') AND DateDiff(d,RequestDate,NotificationDate) <= 15 then 'Y'
when Type = 'Post Service' AND DateDiff(d,RequestDate,NotificationDate) <= 30 then 'Y'
when Type = 'Urgent Preservice' AND DateDiff(d,RequestDate,NotificationDate) <= 3 then 'Y'
when Type = 'Urgent Concurrent' AND DateDiff(d,RequestDate,NotificationDate) <= 3 then 'Y'
ELSE 'N'
END
ELSE
CASE WHEN Status IN ('Denied','Partial Approval') and NotificationDate IS NULL THEN
CASE
when Type in ('Non-Urgent Preservice','Non-Urgent Concurrent') AND DateDiff(d,RequestDate, getdate()) > 15 then 'N'
when Type = 'Post Service' AND DateDiff(d,RequestDate, getdate()) > 30 then 'N'
when Type = 'Urgent Preservice' AND DateDiff(d,RequestDate, getdate()) > 3 then 'N'
when Type = 'Urgent Concurrent' AND DateDiff(d,RequestDate, getdate()) > 3 then 'N'
ELSE ''
END
ELSE 'N/A'
【问题讨论】:
-
Case 语句可以移动到子查询的 where 子句中。如果可行,您可以按日期范围分组,而不是按日期范围重复其他所有内容。
标签: sql sql-server sql-server-2014