Josh,
So you are reviewing a data set and want to know the unique values of a column and how many times they occur in the table. Use this nifty procedure instead of re-writing it each time:
/*
===============================================================================
Procedure: toolbox.GetColumnDataCounts
Author: Josh Jay
Create date: 09/19/2014
Description: Returns the Unique Column Values with Record Counts
ordered by greatest occurrence
===============================================================================
Change | Date | User | Description
===============================================================================
ex
EXEC toolbox.GetColumnDataCounts
@SchemaName = 'dbo',
@TableName = 'MyTable',
@ColumnName = 'MyColumn'
*/
CREATE PROCEDURE [toolbox].[GetColumnDataCounts]
@SchemaName SYSNAME,
@TableName SYSNAME,
@ColumnName SYSNAME
AS
BEGIN
DECLARE @SqlStatement VARCHAR(8000)
SET @SqlStatement =
'select ' + CHAR(10) +
CHAR(9) + '[' + @ColumnName + '] as [' + @SchemaName + '.' + @TableName + '.' + @ColumnName + '],' + CHAR(10) +
CHAR(9) + 'REPLACE(CONVERT(varchar(20), (CAST(count(1) AS money)), 1), ''.00'', '''') as RecordCount ' + CHAR(10) +
'from [' + @SchemaName + '].[' + @TableName + '] ' + CHAR(10) +
'group by [' + @ColumnName + '] ' + CHAR(10) +
'order by count(1) desc;'
PRINT @SqlStatement
EXEC(@SqlStatement)END
No comments:
Post a Comment
Please only include comments that add to the substance of the Blog Post:
- Question or request for clarification
- Idea for improvement
- Identifying an issue
Please refrain from promotion.