我有一个CASE WHEN条件(CompanyGUID和LineGUID),我需要4个不同的计算4个不同的列。 计算工作正常,但我只是想知道是否有任何方法可以使它更方便?例如,在这种情况下可能使用COALESCE技巧?
CASE WHEN dbo.tblCompanyLocations.CompanyGUID = '29634AF7-D0A2-473D-9574-405C23E10F02'
AND dbo.tblQuotes.LineGUID = '1CB72920-B3FC-4822-8030-37B50A2810EB'
THEN isnull(ddaWC.archexMod,1)
END as ExperienceMod,
CASE WHEN dbo.tblCompanyLocations.CompanyGUID = '29634AF7-D0A2-473D-9574-405C23E10F02'
AND dbo.tblQuotes.LineGUID = '1CB72920-B3FC-4822-8030-37B50A2810EB'
THEN case when convert(int,ddawc.premModTtl) <= 0 then 1
when convert(int,ddawc.premModTtl) >= 0
then (1 + ddaWC.premschmod / ddawc.premModTtl) end
END as ScheduleMod,
CASE WHEN dbo.tblCompanyLocations.CompanyGUID = '29634AF7-D0A2-473D-9574-405C23E10F02'
AND dbo.tblQuotes.LineGUID = '1CB72920-B3FC-4822-8030-37B50A2810EB'
THEN isnull(ddaWC.TMpercent,1) END as TerritoryMod,
CASE WHEN dbo.tblCompanyLocations.CompanyGUID = '29634AF7-D0A2-473D-9574-405C23E10F02'
AND dbo.tblQuotes.LineGUID = '1CB72920-B3FC-4822-8030-37B50A2810EB'
THEN case when convert(int,ddaWC.SchedPercent) = 0 or
ddaWC.SchedPercent is not null
then (isnull(ddaWC.archexMod,1)
* (convert(decimal(5,2),isnull(ddaWC.SchedPercent,1))))
* isnull(ddaWC.TMpercent,1)
when ddaWC.SchedPercent is null
then 1 END
END as EffectiveMod
答案 0 :(得分:3)
这样的东西? OUTER APPLY
将执行基于行的选择,如果您的条件未满,则返回NULLs
。否则,它将返回您指定的相同值。只有当你真的需要为所有列提供相同的逻辑时,这才有效。
SELECT otherColumn
,ConditionalColumns.*
FROM YourTable
OUTER APPLY
(
SELECT isnull(ddaWC.archexMod,1) as ExperienceMod,
case when convert(int,ddawc.premModTtl) <= 0 then 1
when convert(int,ddawc.premModTtl) >= 0
then (1 + ddaWC.premschmod / ddawc.premModTtl) end as ScheduleMod,
isnull(ddaWC.TMpercent,1) as TerritoryMod,
case when convert(int,ddaWC.SchedPercent) = 0 or ddaWC.SchedPercent is not null
then (isnull(ddaWC.archexMod,1)
* (convert(decimal(5,2),isnull(ddaWC.SchedPercent,1))))
* isnull(ddaWC.TMpercent,1)
when ddaWC.SchedPercent is null
then 1 END as EffectiveMod
WHERE dbo.tblCompanyLocations.CompanyGUID = '29634AF7-D0A2-473D-9574-405C23E10F02'
AND dbo.tblQuotes.LineGUID = '1CB72920-B3FC-4822-8030-37B50A2810EB'
) AS ConditionalColumns
答案 1 :(得分:1)
像这样:
代码前的某个地方:
Declare @compGuid char(37) = '29634AF7-D0A2-473D-9574-405C23E10F02'
Declare @lineGuid char(37) = '1CB72920-B3FC-4822-8030-37B50A2810EB'
并修改SQL语句中的From Clause以定义别名
cl
的{{1}}和
tblCompanyLocations
的{{1}}
那么SQL代码的Select子句中的情况可以简化为:
q
有点可读......(检查逻辑)