Conditional Select in Calculation

  • I am trying to select several fields from a variety of tables, and also perform a calculation based upon values in those tables. The problem that I have arises when certain fields are null in the calculation. I want to do something similar to the following, but I haven't got it working yet.

    SELECT

    t1.blah1,

    t2.blah2,

    (t1.field1 * t1.field2)/(IF t2.field3 IS NULL THEN t1.field4 ELSE t2.field3)

    FROM

    table1 t1

    left join table2 t3

    ...

    etc

    ...

    Make sense?

  • Try using COALESCE

    SELECT

    t1.blah1,

    t2.blah2,

    (t1.field1 * t1.field2)/COALESCE(t2.field3,t1.field4)

    FROM

    table1 t1

    left join table2 t2

    ____________________________________________________

    Deja View - The strange feeling that somewhere, sometime you've optimised this query before

    How to get the best help on a forum

    http://www.sqlservercentral.com/articles/Best+Practices/61537

Viewing 2 posts - 1 through 1 (of 1 total)

You must be logged in to reply to this topic. Login to reply