sqloracle-databasecount

Column count based on a condition


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
name velocity category id
ABCD 12 A 1
UYIO 44 D 3
ABCF 18 A 1
ABCD 53 A 1
AHYU 53 F 4
ABCD 18 A 1

Can anyone please tell me some solution for this


Solution

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