Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use group by on one column which is having many entries?

I want to use group by on one column which is having many entries

table_a

Name price
AAA  12
BBB  13
AAA  0
CCC  24
AAA  0
DDD  0

Now I want to find out Name which is having Price as 0

but as I'm having entries AAA 3 times I can't directly write simple sql with condition NOT Equal to 0

Please help me I want to print result for above table_a should be

only D as it is having 0 as price.

like image 519
Neo Avatar asked Mar 24 '23 07:03

Neo


2 Answers

I assumed price cannot be lower than zero:

SELECT Name
FROM TableName
GROUP BY Name
HAVING SUM(price) = 0

Or with additional condition of only one price, which is zero

SELECT Name
FROM TableName
GROUP BY Name
HAVING COUNT(*) = 1 AND SUM(price) = 0
like image 154
MarcinJuraszek Avatar answered Mar 26 '23 20:03

MarcinJuraszek


You can achive this by using aggregate functions GROUP BY and HAVING clause as:

SQLFiddle Demo

SELECT name,SUM(price) as price
FROM table 
GROUP BY name
HAVING SUM(price) = 0
like image 35
Omesh Avatar answered Mar 26 '23 20:03

Omesh