How do I convert the number of rows returned into a percentage?

Sure, this is quite easy:

DECLARE @total INT;

SELECT @total = COUNT(*) FROM <TableName>;

WITH [GroupedTable] AS (
    SELECT
       [Name] = <ColumnName>,
       [Count] = SUM(1)
    FROM
       <TableName>
    GROUP BY
       <ColumnName>
)
SELECT
    [Value] = [Name],
    [Percentage] = CAST([Count] AS decimal(19,10)) / @total * 100
FROM 
    [GroupedTable]
ORDER BY
    [Percentage] DESC

the ‘with’ just groups the table by the column, and counts the number of occurrences of that value. The second select just projects this data as a percentage. To get the percentage we just need to count up the total number of rows, which is the what the @total bit does. Hope this helps.

Leave a Comment