Wednesday, September 23, 2015

Generate SQL Statements to Group By Each Column of Table Separately

When working with data with the intent to visualize, there are times when I'll want to group by every column in a table, separately, one at a time, to determine the possible values in that column.

I do this often enough I created a simple SQL Query to build these group by statements for me:

declare @table_name varchar(200) = 'dbo.mytablename'
'select ' + + ', count(1) cnt from ' + @table_name + ' group by ' + + ' order by 2 '
from sys.columns c
where c.object_id = object_id(@table_name)

Hope this helps,

Post a Comment