有没有办法使这个带有嵌套Case语句的SQL代码更干净?
我有一个查询,根据一个变量可以是10个不同的选项,我会做一些稍微不同的事情有没有办法使这个带有嵌套Case语句的SQL代码更干净?,sql,sql-server,Sql,Sql Server,我有一个查询,根据一个变量可以是10个不同的选项,我会做一些稍微不同的事情 ( CaCartons + case when PgFeet is null or PgWeight is null then 0 else COALESCE( case when CLIENTNAME ='01' then case
(
CaCartons
+
case when PgFeet is null or PgWeight is null then 0 else
COALESCE(
case when CLIENTNAME ='01' then
case
when PgWeight < @CartonMaxWeight and PgFeet < @CartonMaxVolume01
then 1
when PgWeight / @CartonMaxWeight >= PgFeet / @CartonMaxVolume01
then PgWeight / @CartonMaxWeight
else
PgFeet / @CartonMaxVolume01
end
else null end,
case when CLIENTNAME ='02' then
case
when PgWeight < @CartonMaxWeight and PgFeet < @CartonMaxVolume02
then 1
when PgWeight / @CartonMaxWeight >= PgFeet / @CartonMaxVolume02
then PgWeight / @CartonMaxWeight
else
PgFeet / @CartonMaxVolume02
end
else null end,
case when CLIENTNAME ='03' then
case
when PgWeight < @CartonMaxWeight and PgFeet < @CartonMaxVolume03
then 1
when PgWeight / @CartonMaxWeight >= PgFeet / @CartonMaxVolume03
then PgWeight / @CartonMaxWeight
else
PgFeet / @CartonMaxVolume03
end
else null end
)
end
) TotalCartons
还有10个客户名
有没有办法使这段代码更简洁易读 我会在FROM子句中加入更多的逻辑。我想这就是你想要的逻辑:
select . . .,
(CaCartons +
(case when PgFeet is null or PgWeight is null then 0
when PgWeight < @CartonMaxWeight and PgFeet < v.CartonMaxVolume01
then 1
when PgWeight / @CartonMaxWeight >= PgFeet / v.CartonMaxVolume01
then PgWeight / @CartonMaxWeight
else PgFeet / v.CartonMaxVolume01
end)
)
from t left join
(values ('client01', @CartonMaxVolume01),
('client02', @CartonMaxVolume02),
. . .
) v(client, CartonMaxVolume)
on t.client = v.client
要在查询中的多个位置重构和重用表达式,可以将其提升到公共表表达式中,然后从中进行选择。例如:
with q as
(
select *,
case when CLIENTNAME ='01' then @CartonMaxVolume01
when CLIENTNAME ='02' then @CartonMaxVolume02
when CLIENTNAME ='03' then @CartonMaxVolume03
else null end ClientCartonMaxVolume
from ...
)
select
CaCartons
+
case when PgFeet is null or PgWeight is null then 0
when PgWeight < @CartonMaxWeight and PgFeet < ClientCartonMaxVolume then 1
when PgWeight / @CartonMaxWeight >= PgFeet / ClientCartonMaxVolume
else PgFeet / ClientCartonMaxVolume end as TotalCartons
from q;
这是一个格表达式;T-SQL中没有Case语句。