0

There are no rows for this product_id. Result returns no rows instead of SUM = 0.

 SELECT COALESCE(SUM(amount), 0) FROM store2product WHERE product_id = 6706434 GROUP BY product_id;

Is there a way to get result = 0?

6
  • Is amount definitely a numeric field? COALESCE will only return zero if SUM returns NULL, which presumably it is not. Commented Nov 25, 2016 at 10:10
  • amount is SMALLINT NOT NULL Commented Nov 25, 2016 at 10:11
  • 2
    Obviously you don’t get a record in the result set if there is no record that matches your WHERE clause. You'll need a JOIN or subquery of some sorts. Commented Nov 25, 2016 at 10:12
  • are you sure that the WHERE product_id = 6706434 return rows? Commented Nov 25, 2016 at 10:13
  • 1
    Remove group by Commented Nov 25, 2016 at 10:19

2 Answers 2

1

There is no record for product_id = 6706434 in table store2product. As you group by product_id, you get one result row per product_id found with this query. As the product_id is not found, no row is returned.

Simple solution: remove GROUP BY.

SELECT 
  COALESCE(SUM(amount), 0) 
FROM store2product 
WHERE product_id = 6706434;

Now you get one result row in any case.

Sign up to request clarification or add additional context in comments.

Comments

0

Try this Trick..

Schema for your case

CREATE TABLE #TAB (ID INT, AMT DECIMAL(18,2))
INSERT INTO #TAB
SELECT 1,1200
UNION ALL
SELECT 1,120
UNION ALL 
SELECT 3, 100

Now query the table like

SELECT SUM(ISNULL(AMT,0)) AS AMT  FROM (

SELECT  ID, SUM(AMT)AMT FROM #TAB WHERE ID =2   GROUP BY ID
UNION ALL
SELECT NULL AS ID, NULL AS AMT

)A

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.