Question

The following query results value as single row either as value for ExtendedText or zero for matching LineNumber in the table data. I need to add one more condition in the query as - if the LineNumber doesn't exist return one row as zero as same in the case of null. The query should check both for NULL and empty to return zero

SELECT  ISNULL(Sum(convert(dec,DeliveryPaymentExtras.ExtendedText)),0) As ExtendedText
FROM    DeliveryPaymentExtras
WHERE   (LineNumber =21) group by LineNumber
Was it helpful?

Solution

If you want the result for only one LineNumber value, as the code suggests, it's trivial. Just remove the GROUP BY LineNumber. An aggregation without group by means that the result will be exactly one row, no matter if we have 0 or a million rows, before the aggregation:

SELECT  ISNULL(Sum(convert(dec,DeliveryPaymentExtras.ExtendedText)),0) AS ExtendedText
FROM    DeliveryPaymentExtras
WHERE   (LineNumber =21) ;

If you want results for multiple values (for example if you had: WHERE LineNumber IN (21, 34, 55) GROUP BY LineNumber), then it's not straightforward. One way is:

SELECT  v.LineNumber,
        ISNULL(Sum(convert(dec,d.DeliveryPaymentExtras.ExtendedText)),0) 
            AS ExtendedText
FROM    ( VALUES (21),(34),(55)
        ) AS v (LineNumber)
    LEFT JOIN DeliveryPaymentExtras AS d
        ON d.LineNumber = v.LineNumber
GROUP BY v.LineNumber ;

OTHER TIPS

Select your value into a variable, and select that variable.

Your issue is that NULL number of rows will not trigger your ISNULL which evaluates the SUM and not the number of rows in the query. It's a different mechanic.

So you'll need to select your ISNULL sum into a variable, and then select from that in your query:

Something like this:

DECLARE @Result DECIMAL(18,4)
SET @Result = 
(
SELECT  Sum(convert(dec,DeliveryPaymentExtras.ExtendedText)) As ExtendedText
FROM    DeliveryPaymentExtras
WHERE   (LineNumber =21) group by LineNumber
(


SELECT ISNULL(@Result, 0)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top