question

James Moore avatar image
James Moore asked

Count of distinct values by column

What is the best way to get the count of the distinct values in each column of a table?

t-sqlsql-server
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

1 Answer

·
TimothyAWiseman avatar image
TimothyAWiseman answered

If there are a few columns, simply do something like:

Select 
   count(distinct col1) as NumCol1,
   count(distinct col2) as NumCol2
from
  tableName

If there numerous columns then you can use dynamic sql to get every single one of them, for instance:

declare @sql varchar(max)
declare @tablename varchar(128)

set @tableName = 'TestTable'

select @sql = 'select' + char(10)

select @sql = @sql + ' count(distinct ' + Column_name + ') as Num' + Column_name + ', ' + char(10)
from information_schema.columns
where table_name = @tableName

--remove the last comma
set @sql = substring(@sql, 1, len(@sql) - 3) + char(10)

select @sql = @sql + 'from ' + @tableName

print @sql
exec (@sql)
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

Write an Answer

Hint: Notify or tag a user in this post by typing @username.

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.