这是另一个使用子查询的蛮力攻击。设置一些测试数据:
CREATE TABLE MyTable
(
Id int not null
,Col1 char(1) null
,Col2 char(1) null
,Col3 char(1) null
,Col4 char(1) null
)
INSERT MyTable
select 1, 'Y', 'Y', 'Y', 'Y'
union all select 2, 'Y', null, 'N', null
union all select 3, 'Y', null, null, null
union all select 4, null, null, null, null
我使用字符数据作为目标值,但将其设为数字应该没有问题。我添加了第四行来检查除以零(感谢 ps!)。所以,
SELECT
mt.ID
,case mt.Col1 when 'Y' then xx.distrib else 0 end
,case mt.Col2 when 'Y' then xx.distrib else 0 end
,case mt.Col3 when 'Y' then xx.distrib else 0 end
,case mt.Col4 when 'Y' then xx.distrib else 0 end
from MyTable mt
inner join (select
ID
,1.0 / ( case Col1 when 'Y' then 1 else 0 end
+ case Col2 when 'Y' then 1 else 0 end
+ case Col3 when 'Y' then 1 else 0 end
+ case Col4 when 'Y' then 1 else 0 end) distrib
from MyTable) xx
on xx.Id = mt.Id
似乎产生了预期的结果。 (单独运行子查询,你会得到除以零......但老实说,我不知道为什么运行整个查询不会。