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
'select ' + c.name + ', count(1) cnt from ' + @table_name + ' group by ' + c.name + ' order by 2 '
from sys.columns c
where c.object_id = object_id(@table_name)
Hope this helps,
Aaron
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
'select ' + c.name + ', count(1) cnt from ' + @table_name + ' group by ' + c.name + ' order by 2 '
from sys.columns c
where c.object_id = object_id(@table_name)
Hope this helps,
Aaron
Comments