Count number of groups present in column using SQL Server 2008 -
i have table shown below:
create table test ( cola varchar(10) )
inserting data:
insert test values('a'); insert test values('a'); insert test values('a'); insert test values('b'); insert test values('b'); insert test values('c'); insert test values('d'); insert test values('d');
i want show how many groups present in column cola
expected result:
totalgroups b c d -------------------------------- 4 3 2 1 2
try this, removing [ , ] avoid sql injections:
declare @sql varchar(max) = 'select (select count(distinct cola) test) totalgroups' select @sql += ',' +cast(count(*) varchar(10)) + '['+ replace(replace(cola, ']', ''), '[', '') + ']' test group cola order cola exec(@sql)
result:
total_groups b c d 4 3 2 1 2
Comments
Post a Comment