Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Column count based on a condition

Tags:

count

oracle

I have created an oracle query like as shown below,the query is working fine but the problem is that I want one more column which is the count of name where category should be A and id should be 1

SELECT name, velocity, COUNT(*) AS count, category FROM section GROUP BY name, velocity

enter image description here

Can anyone please tell me some solution for this

like image 261
Alex Man Avatar asked Oct 16 '15 11:10

Alex Man


People also ask

Which formula will count based on a condition?

The Excel COUNTIFS function returns the count of cells that meet one or more criteria. COUNTIFS can be used with criteria based on dates, numbers, text, and other conditions.


2 Answers

SELECT name, velocity, COUNT(*) AS count, 
COUNT(CASE WHEN category = 'A' AND id = 1 THEN 1 END)
FROM section 
GROUP BY name, velocity

This should work.

If record does not meet the condition then it will return a NULL, and count skips NULL fields.

like image 180
Canburak Tümer Avatar answered Sep 21 '22 04:09

Canburak Tümer


Something like this:

SELECT name, velocity, COUNT(*) AS count, 
SUM(CASE WHEN category = 'A' AND id = 1 THEN 1 ELSE 0 END)
FROM section 
GROUP BY name, velocity
like image 31
Tatiana Avatar answered Sep 21 '22 04:09

Tatiana