using ISNULL and SUM on the same column

  • I want to generate a report to compare the estimated_total_fee (on the usr_int1 table) with the amount the customer has actually been billed (from ac_billbook.costsnet).

    Customers and their orders are identified by matters.entityref for the customer, and matters.number for the order number. Some customers may have had more than one bill generated on the same order; I don't need to know the details of every bill, just the total the customer has been billed for the one order so I'm using the Sum function.

    However, I also need to account for orders that have not yet been billed so I want to include IsNull to allow for null values in the Ac_Billbook.costsnet column. I'm not sure how to phrase the syntax to allow for both Sum and IsNull on the same column.

    SELECT

    Matters.EntityRef,

    Matters.Number,

    usr_Int1.Estimated_total_fee,

    Sum(Ac_Billbook.CostsNet) AS SumOfCostsNet

    FROM

    Ac_Billbook INNER JOIN

    (Usr_Int1 INNER JOIN Matters ON

    (Usr_Int1.MatterNo = Matters.Number)

    AND (Usr_Int1.EntityRef = Matters.EntityRef))

    ON (Ac_Billbook.MatterRef = Usr_Int1.MatterNo)

    AND (Ac_Billbook.EntityRef = Usr_Int1.EntityRef)

    Any help help gratefully received!

    Thanks

  • A couple of things:

    1. You need a GROUP BY on your query.

    2. You can address NULL values for Ac_Billbook.CostsNet 2 ways. You wrap the SUM with an ISNULL, ISNULL(Sum(Ac_Billbook.CostsNet), 0) because SUM ignores nulls when summing or you can reverse the SUM and ISNULL like this, Sum(ISNULL(Ac_Billbook.CostsNet, 0)) which will convert individual NULL's to 0. Doesn't really matter which one you do. The first might perform slightly better because the ISNULL is only being applied once. I've never actually tested it.

  • Jack Corbett (5/30/2012)


    A couple of things:

    1. You need a GROUP BY on your query.

    2. You can address NULL values for Ac_Billbook.CostsNet 2 ways. You wrap the SUM with an ISNULL, ISNULL(Sum(Ac_Billbook.CostsNet), 0) because SUM ignores nulls when summing or you can reverse the SUM and ISNULL like this, Sum(ISNULL(Ac_Billbook.CostsNet, 0)) which will convert individual NULL's to 0. Doesn't really matter which one you do. The first might perform slightly better because the ISNULL is only being applied once. I've never actually tested it.

    That's not actually true - they are not equivalent.

    ISNULL(SUM(Ac_Billbook.CostsNet), 0) should be preferred - SUM will as you say ignore null values. However, if there are zero records to sum over, SUM will return NULL. Most of the time when doing a SUM you would want to treat zero records as having an aggregate sum of zero.

  • please add GROUP BY in your query

    ISNULL(SUM(Ac_Billbook.CostsNet), 0)

Viewing 4 posts - 1 through 3 (of 3 total)

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