18

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,753
  • 72
  • 57
  • 129
Alex Man
  • 4,746
  • 17
  • 93
  • 178
  • 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

45
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
  • 993
  • 17
  • 36
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
  • 10
  • 19
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
  • 201,996
  • 37
  • 293
  • 362