After a query I end up with a table like this
tbl_1
:
category type count cpg b 1 auto c 1 cpg c 1 auto v 1
I would like to calculate the total_count by category
, and the percentage of count that is not (type<>'v'
) also by category in SQL.
Any ideas how I could do that ?
The resulting table should look like this:
category total_count percentage cpg 2 1 auto 2 0.5
Advertisement
Answer
Is this what you want?
select category, sum(count), sum(case when type <> 'v' then count else 0.0 end) / sum(count) from t group by category;
From the original table, you could just do:
select category, count(*) as cnt, avg(case when type <> 'v' then 1.0 else 0 end) as ratio from tbl1 group by category;