14

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

Brian Tompsett - 汤莱恩
  • 5,438
  • 68
  • 55
  • 126
Alex Man
  • 4,508
  • 16
  • 78
  • 160
  • Possible duplicate of [Conditional Count on a field](http://stackoverflow.com/questions/1288058/conditional-count-on-a-field) – C8H10N4O2 Apr 06 '17 at 15:21

3 Answers3

41
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.

Canburak Tümer
  • 951
  • 20
  • 35
3

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
Tatiana
  • 1,489
  • 8
  • 18
1
SELECT name, velocity, COUNT(*) AS count, category, 
       (select count(distinct name) from section where category = 'A' and id = 1)
FROM section 
GROUP BY name, velocity
juergen d
  • 195,137
  • 36
  • 275
  • 343