RekKA
RekKA

Reputation: 150

GROUP BY in SQL is not giving correct result

http://sqlfiddle.com/#!9/62003/3

In above fiddle, there are 4 different subid and query is GROUP BY on subid. But it's giving 0 for all subid after GROUP BY.

Please advise on why it is not giving 10 and 20 as result for 2 subid? What wrong I am doing in query? Please let me know.

Upvotes: 1

Views: 90

Answers (1)

Lukasz Szozda
Lukasz Szozda

Reputation: 175606

When you use GROUP BY you get result for each group. If you want to skip them use HAVING:

SELECT SUM(shippingvalue) AS shippingvalue
FROM t_product_purchase 
WHERE mpkid=5 
GROUP BY subid
HAVING shippingvalue <> 0;

SqlFiddleDemo

Output:

╔═══════════════╗
║ shippingvalue ║
╠═══════════════╣
║            10 ║
║            20 ║
╚═══════════════╝

If you want subid in resultset use:

SELECT subid, SUM(shippingvalue) AS shippingvalue
FROM t_product_purchase 
WHERE mpkid=5 
GROUP BY subid
HAVING shippingvalue <> 0

SqlFiddleDemo2

Upvotes: 3

Related Questions