COALESCE with MIN

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Cinnamon girl
    New Member
    • Feb 2012
    • 3

    COALESCE with MIN

    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
    Code:
    CASE WHEN [denominator]= '0'
    THEN '0'
    ELSE MIN([numerator]/[denominator]) END AS'MIN([numerator]/[denominator])'
    ,CASE WHEN [denominator]= '0'
    THEN '0'
    ELSE MAX([numerator]/[denominator]) END AS'MAX([numerator]/[denominator])'
    ,CASE WHEN [denominator]= '0'
    THEN '0'
    ELSE AVG([numerator]/[denominator]) END AS'AVG([numerator]/[denominator])'
    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
    Code:
    MIN(COLASCE([numerator]/[denominator])) AS 'MIN([numerator]/[denominator])'
    I need some guidance in making this code better and workable.
    Thanks in advance for your time and suggestions.

    -Cinnamongirl.
  • Rabbit
    Recognized Expert MVP
    • Jan 2007
    • 12517

    #2
    Coalesce will work if the denominator is null, not if it's 0.

    Comment

    • ck9663
      Recognized Expert Specialist
      • Jun 2007
      • 2878

      #3
      Try using a CTE instead.


      ~~ CK

      Comment

      • Cinnamon girl
        New Member
        • Feb 2012
        • 3

        #4
        How do I use CTE in a recursive manner for other columns while aggregating the table grouping on hour or day or week?

        Comment

        • ck9663
          Recognized Expert Specialist
          • Jun 2007
          • 2878

          #5
          Here, try this:

          Code:
          with prepared_data
          as
          (
             select 
                numerator, denominator, 
                fraction = 
                   case 
                      when denominator = 0 then 0.00                        
                      else numerator/denominator
                   end
             from YourTable  
          )
          select
             min(fraction), max(fraction), avg(fraction)
          from prepared_data
          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

          Comment

          • Cinnamon girl
            New Member
            • Feb 2012
            • 3

            #6
            It works...Thank you CK

            Comment

            Working...