I have following query
Select
a,b,c,
case totalcount
when 0 then 0
else abcd/totalcount
end AS 'd',
case totalcount
when 0 then 0
else defg/totalcount
end AS 'e'
From
Table1
In this query, I have same case statement in select query…Can i make it into single select statement.
“totalcount” is some value… abcd and defg are two column values from table1. If totalcount is zero, i dont want to divide, else I wish to divide to get an average value of abcd and defg.
At first view, I would say no, since you seem to use the exact same condition leading to different results.
Besides, this looks odd to me, why would you need two
SELECT CASEfor only one condition? This makes no sense.Could you be more specific or give a real-world example of what you’re trying to ask, with “real” data so that we might better answer your question?
EDIT #1
Given that:
I would still answer no, as if they are two different fields, and you want both results in your result set, then you will need to write two
CASEstatements, one for each of the fields you need to verify whether it is zero-valued or not. Keep in mind that oneCASEstatement is equivalent to one single column only. So, if you need to check for a zero value, you are required to check for both independently.By the way, sorry for my misunderstanding, that must be a language barrier, unfortunately. =) But my requirement for “real” data example holds, since this might light us all up with some other related solutions, we never know! =)
EDIT #2
Considering you have to check for a value of
0, I would perhaps rewrite my code as follows, for the sake of readability:In my opinion, it is leaner and swifter in the code, and it is easier to understand what is the intention. But after all, the result would be the same! No offense made here! =)
EDIT #3
After having read your question edit:
I say, if it is the average that you’re after, why not just use the
AVGfunction which will deal with it internaly, without having to care about zero values?Plus, considering having no record, the average can only be 0!
I don’t know about your database engine, but if it is Oracle or SQL Server, and I think DB2 as well, they support this function.