3

I'm trying to perform a SUM function, but I only want it to return a value if all the fields are not null. Right now when it performs the SUM, it skips over NULL values and just adds up the non-nulls. What I would like to happen is, if even one value is null in the sum, it'll just return null. Here is a sample table:

  Table_1
  -------------
  Price   Quant
  10.00 |  NULL
  11.00 |  100 

Here is the query I'm running:

SELECT SUM((Price * Quant)) FROM [Table_1]

At this point, it returns a value of 1100. I'd like it to return NULL instead since the first record's Price * Quant is null.

5 Answers 5

3

You can do something like:

Select 
  case when count(
    case when price + quant is null then 1 end
  ) = 0 then sum(price*quant) end as val
From your_table;

We are checking price + quant for null because null + anything is null, if either price or quant is null, it will return null. You can of course use other arithmetic operation, but I think sum is lightest one.

You can also do separate checks:

Select 
  case when count(
    case when price is null or quant is null then 1 end
  ) = 0 then sum(price*quant) end as val
From your_table;
Sign up to request clarification or add additional context in comments.

Comments

0
    SELECT SUM((Price * Quant)) FROM [Table_1]
 WHERE Price IS NOT NULL WHERE Quant IS NOT NULL

You can run this script

3 Comments

I think you mean WHERE Price IS NOT NULL AND Quant IS NOT NULL
Yes i mean this
Well, you could have updated your answer when you were told of your mistake. Anyway, your query gets the same result as OP's query. Seems you haven't understood the request.
0

I would do it like this...

SELECT
    CASE
        WHEN MAX(T2.NoValue) IS NOT NULL
            THEN NULL
        ELSE SUM(Price * Quant)
    END AS Total
FROM Table_1 T1
LEFT JOIN
(
    SELECT TOP 1 1 AS NoValue
    FROM Table_1 
    WHERE Quant IS NULL
    OR Price IS NULL
) T2
    ON NoValue = 1
;

Comments

0

How about this way:

SELECT case when Quant is null then null else SUM((Price * Quant)) as this_sum end FROM [Table_1]

Comments

0

If you want to test for nullness of both Price and Quant, you can use the following:

-- Sample T-SQL schema to demonstrate the SQL query
DECLARE @tb TABLE
(
    Price INT NULL,
    Quant INT NULL
)

INSERT INTO @tb(price, quant) VALUES (10, null)
INSERT INTO @tb(price, quant) VALUES (20, 100)

IF EXISTS(SELECT 1 FROM @tb WHERE (price + quant) IS NULL)
    SELECT NULL AS C
ELSE
    SELECT SUM(price * quant) AS C
    FROM @tb

If you just need to test for quant, then replace "(price + quant)" with use "quant".

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.