Get frequency of a column in SQL Server

46,730

Solution 1

Use aggregate functions

 Select column, count(*)
 From   table
 Group By column

This will return one row that contains the count, for each distinct value in column

Solution 2

One row each value:

select column 'value', count (column) 'Frequency'
from table
group by column

if only 2 values this give you both results in one row

select sum(case when column=1 then 1 else 0 end) as '1 Frequency',
        sum(case when column=2 then 1 else 0 end) as '2 Frequency'
from table
Share:
46,730
user_012314112
Author by

user_012314112

Updated on August 03, 2022

Comments

  • user_012314112
    user_012314112 almost 2 years

    I have a column with values like 1,1,2,1,... and I would want to get the frequency of 1 and 2, I did

    SELECT count(column)
    FROM table
    WHERE column = 1;
    
    SELECT count(column)
    FROM table
    WHERE column = 2;
    

    But, could I take the frequency with a more direct way?

  • Horaciux
    Horaciux over 9 years
    @user_012314112 Have you tried my answer? Let me know if it works or need some tunning.