364,111 Members | 2129 Browsing Online
Community for Developers & IT Professionals
Bytes IT Community

COALESCE with MIN

Cinnamon girl
P: 3
Hello all,

I' trying to query a table(detailed) which has two columns of which one is numerator and the other is denominator part of a field.
I get '0' for denominator for some rows and as it returns NULL I get an error "divide by zero".
So, I'm using a CASE statement like
Expand|Select|Wrap|Line Numbers
  1. CASE WHEN [denominator]= '0'
  2. THEN '0'
  3. ELSE MIN([numerator]/[denominator]) END AS'MIN([numerator]/[denominator])'
  4. ,CASE WHEN [denominator]= '0'
  5. THEN '0'
  6. ELSE MAX([numerator]/[denominator]) END AS'MAX([numerator]/[denominator])'
  7. ,CASE WHEN [denominator]= '0'
  8. THEN '0'
  9. ELSE AVG([numerator]/[denominator]) END AS'AVG([numerator]/[denominator])'
  10.  
  11.  
Now I have to involve my [denominator] into an aggregate function in the GROUP BY clause,which I donot want.
I know this way of writing code is a bit DUMB because I have about 60 more columns on which I have to do this.

So, I was wondering if a COLAESCE function can be used here as
Expand|Select|Wrap|Line Numbers
  1. MIN(COLASCE([numerator]/[denominator])) AS 'MIN([numerator]/[denominator])'
  2.  
I need some guidance in making this code better and workable.
Thanks in advance for your time and suggestions.

-Cinnamongirl.
Feb 13 '12 #1
Share this Question
Share on Google+
5 Replies


Rabbit
Expert Mod 5K+
P: 6,668
Coalesce will work if the denominator is null, not if it's 0.
Feb 13 '12 #2

ck9663
Expert 2.5K+
P: 2,732
Try using a CTE instead.


~~ CK
Feb 13 '12 #3

Cinnamon girl
P: 3
How do I use CTE in a recursive manner for other columns while aggregating the table grouping on hour or day or week?
Feb 14 '12 #4

ck9663
Expert 2.5K+
P: 2,732
Here, try this:

Expand|Select|Wrap|Line Numbers
  1.  
  2. with prepared_data
  3. as
  4. (
  5.    select 
  6.       numerator, denominator, 
  7.       fraction = 
  8.          case 
  9.             when denominator = 0 then 0.00                        
  10.             else numerator/denominator
  11.          end
  12.    from YourTable  
  13. )
  14. select
  15.    min(fraction), max(fraction), avg(fraction)
  16. from prepared_data
  17.  
  18.  
Remember, all the function you use ignores NULL, by default.

Also if both numerator and denominator are integer, the quotient will be integer as well.

Happy Coding!!!


~~ CK
Feb 15 '12 #5

Cinnamon girl
P: 3
It works...Thank you CK
Feb 15 '12 #6

Post your reply

Help answer this question



Didn't find the answer to your Microsoft SQL Server question?

You can also browse similar questions: Microsoft SQL Server coallesce function min function