我想用一个CASE
语句来清理一些,现在它运行大约 10 秒。希望将其压缩以及冗余代码调用。想知道是否有比CASE
.
有 3 个独立的代码块。除了根据队列中的天数分配颜色之外,每个块都做几乎完全相同的事情。
绿色 少于 1 天。黄色任何大于 1 天但小于 3 天的东西。红色超过 3 天。
select m.number, 'status1', 'Green', datediff(day, (select max(datechanged) from statushistory where accountid = m.number), getdate())
from master m with (nolock)
inner join customer c with (nolock) on m.customer = c.customer
where m.status = 'status1'
and datediff(day, (select max(sh.datechanged) from statushistory sh where accountid = m.number), getdate()) <= 1
and qlevel < 998
and (m.desk not like 'ATY%')
and (isnull(m.link,0) = 0 or m.linkdriver = 1)
and m.desk not in ('param1','param2','param3','param4','param5','param6','param7','param8','param9','param10','param11','param12')
select m.number, 'status1', 'Yellow', datediff(day, (select max(datechanged) from statushistory where accountid = m.number), getdate())
from master m with (nolock)
inner join customer c with (nolock) on m.customer = c.customer
where m.status = 'status1'
and datediff(day, (select max(sh.datechanged) from statushistory sh where accountid = m.number), getdate()) between 1 and 2
and qlevel < 998
and (m.desk not like 'ATY%')
and (isnull(m.link,0) = 0 or m.linkdriver = 1)
and m.desk not in ('param1','param2','param3','param4','param5','param6','param7','param8','param9','param10','param11','param12')
select m.number, 'status1', 'Red', datediff(day, (select max(datechanged) from statushistory where accountid = m.number), getdate())
from master m with (nolock)
inner join customer c with (nolock) on m.customer = c.customer
where m.status = 'status1'
and datediff(day, (select max(sh.datechanged) from statushistory sh where accountid = m.number), getdate()) >= 3
and qlevel < 998
and (m.desk not like 'ATY%')
and (isnull(m.link,0) = 0 or m.linkdriver = 1)
and m.desk not in ('param1','param2','param3','param4','param5','param6','param7','param8','param9','param10','param11','param12')
编辑#1
select m.number, 'status1',
CASE
WHEN datediff(day, (select max(sh.datechanged) from statushistory sh where accountid = m.number), getdate()) <= 1 THEN 'Green'
WHEN datediff(day, (select max(sh.datechanged) from statushistory sh where accountid = m.number), getdate()) between 1 and 3 THEN 'Yellow'
WHEN datediff(day, (select max(sh.datechanged) from statushistory sh where accountid = m.number), getdate()) > 3 THEN 'Red'
END
, datediff(day, (select max(datechanged) from statushistory where accountid = m.number), getdate())
from master m with (nolock)
inner join customer c with (nolock) on m.customer = c.customer
where m.status = 'status1'
--and datediff(day, (select max(sh.datechanged) from statushistory sh where accountid = m.number), getdate()) <= 1
and qlevel < 998
and (m.desk not like 'ATY%')
and (isnull(m.link,0) = 0 or m.linkdriver = 1)
and m.desk not in ('param','param','param','param','param','param','param','param','param','param','param','param')