This is not really a problem because I solved it. But, I wanted to share something that ate my brain today. So, run this query and check it out:
The query:
select 2 as ID1,0 as ID2 into #TEMP
insert into #TEMP (ID1,ID2)
values (2,1),(2,2),(2,0)
select
case when min(case when ID1=2 and ID2=0 then 0
else 1
end)=0 then 0
else sum(log(ID2))
end
from #TEMP
The fix:
select
case when min(case when ID1=2 and ID2=0 then 0
else 1
end)=0 then 0
else sum(log(case when ID1=2 and ID2<>0 then ID2
else 1
end))
end
from #TEMP
My query was larger and more difficult to debug, but what do you say about the plan that MSSQL is making and the fact that it gets it wrong with this query? How can it be modified to work except my little fix that I showed before? I am guessing that computing scalars before the query would make things slow if the scalars are not easy to compute and we compute for all values.