sqloracle10g

Select COUNT in multiple columns with separate condition


Assuming I have these columns :

id status date
1 success 2-Mar-25
1 failed 4-Apr-25
2 success 1-May-25
3 success 22-May-25
2 NULL 12-Jul-25
4 NULL 15-Jul-25

How can I provide the result below, directly from table?

total_trial success failed
6 3 1

Solution

  • Although Oracle 10g comes from… long, long ago, you should be able to get this by counting conditioned values:

    select
      count(*) total_trial,
      count(case when status = 'success' then 1 end) success,
      count(case when status = 'failed' then 1 end) failed
    from t;
    

    This relies on case returning null when not matching, and count ignoring nulls in its total.

    Alternatively you can sum up 1s when matching and 0s when not matching:

    select
      count(*) total_trial,
      sum(case when status = 'success' then 1 else 0 end) success,
      sum(case when status = 'failed' then 1 else 0 end) failed
    from t;
    

    Both return the expected:

    TOTAL_TRIAL SUCCESS FAILED
    6 3 1

    You can see both versions running in a live demo.