Wednesday, June 24, 2015

sql - count total rows,subset of rows and percentage

Recently in one of the projects, I had to get the total number of rows along with count of a subset of rows and the percentage of the subset of rows compared to the total rows.

The table structure is very simple with just two columns Id,Match.The Id column is of type int and Match column takes two values 'Y' and 'N' indicating whether a match was found or not in the given Id.We use this table as a reporting table to record some activity.

For reporting purposes we wanted to get the total records sent for match in a given week and wanted to know the success rate.

Below is the query to get the total count,match count,nomatch count and the success rate.

select 
        id,count(*) total,
count(case when match='Y' then 1 end) match,
count(case when match='N' then 1 end) nomatch, 
(cast(count(case when match='Y' then 1 end) as float)/cast(count(*) as float)) * 100 successrate
from 
        my_table
group by 
        id
order by 
        id desc 




No comments: