Divide by 0 Error

  • I am running this query, and for the most part it works just fine.

    however when i place certain dates in the @fromdate and @todate. i get a divide by zero error. i cannot seem to fix this. i need a code that says AND NOT if sum(trxcount) or sum(trxquantity) = 0. anything right now will help.

    WITH original_cte (rmssalesrepido, rmssalesrepnameo, locncodeo, locndscro,

    [Trx Counto], [Trx Qtyo], upto )

    AS (SELECT rmssalesrepid AS rmssalesrepido,

    rmssalesrepname AS rmssalesrepnameo,

    locncode AS locncodeo,

    locndscr AS locndscro,

    CONVERT(INT, SUM(trxcount)) AS [Trx COUNT],

    SUM(trxquantity) AS [Trx Qty],

    SUM(trxquantity) / SUM(trxcount) AS [UPTo]

    FROM dbo.icl_sockeye_flashreport

    WHERE ( docdate >= 'jan 1 2011'

    AND docdate <= 'feb 28 2011' )

    AND ( NOT ( department IN ( 'MISS', 'TEST' ) ) )

    AND ( NOT ( rmssalesrepname IN ( '101', '999' ) ) )

    AND ( NOT ( salespersonzip = '0' ) )

    AND locncode = salespersonstate

    GROUP BY rmssalesrepid,

    rmssalesrepname,

    locncode,

    locndscr,

    salespersonzip)

    SELECT rmssalesrepid,

    rmssalesrepname,

    locncode,

    locndscr,

    [UPTo],

    CONVERT(INT, SUM(trxcount)) AS [Trx COUNT],

    SUM(trxquantity) AS [Trx Qty],

    SUM(trxquantity) / SUM(trxcount) AS [UPT]

    FROM dbo.icl_sockeye_flashreport

    INNER JOIN original_cte

    ON rmssalesrepid = original_cte.rmssalesrepido

    WHERE ( docdate >= @fromdate

    AND docdate <= @todate )

    AND ( NOT ( department IN ( 'MISS', 'TEST' ) ) )

    AND ( NOT ( rmssalesrepname IN ( '101', '999' ) ) )

    AND ( NOT ( salespersonzip = '0' ) )

    AND locncode = salespersonstate

    GROUP BY rmssalesrepid,

    rmssalesrepname,

    locncode,

    locndscr,

    salespersonzip,

    [UPTo]

    ORDER BY rmssalesrepid

  • Use HAVING clause

    Like HAVING (sum(colA) <> 0 and sum(colB) <>0 )

  • Replace

    SUM(trxquantity) / SUM(trxcount) AS [UPT]

    WITH

    CASE WHEN SUM(trxcount) > 0 THEN SUM(trxquantity) / SUM(trxcount) ELSE 0 END AS [UPT]

    Seth Phelabaum


    Consistency is only a virtue if you're not a screwup. 😉

    Links: How to Post Sample Data[/url] :: Running Totals[/url] :: Tally Table[/url] :: Cross Tabs/Pivots[/url] :: String Concatenation[/url]

  • Replace this:

    SUM(trxquantity) / SUM(trxcount)

    with this:

    SUM(trxquantity) / NULLIF(SUM(trxcount),0)

  • Garadin (4/12/2011)


    Replace

    SUM(trxquantity) / SUM(trxcount) AS [UPT]

    WITH

    CASE WHEN SUM(trxcount) > 0 THEN SUM(trxquantity) / SUM(trxcount) ELSE 0 END AS [UPT]

    Thank you this worked perfectly !!

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

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