get a count of each value from every column in a table SQL Server

前端 未结 3 1875
庸人自扰
庸人自扰 2021-01-14 20:20

So I looked this up and this question is very similar but it\'s missing a key piece: SQL Server count number of distinct values in each column of a table

So in that

3条回答
  •  北荒
    北荒 (楼主)
    2021-01-14 20:41

    You could use:

    DECLARE @Table SYSNAME = 'TableName'; 
    DECLARE @SQL NVARCHAR(MAX) = ''
    SELECT @SQL = STUFF((SELECT ' UNION SELECT ''' + name 
                                + ''' AS [Column], ' 
                                + 'CAST(' + QUOTENAME(Name)
                                + ' AS NVARCHAR(MAX)) AS [ColumnValue], COUNT(*) AS [Count] FROM ' 
                                + QUOTENAME(@Table) + ' GROUP BY ' + QUOTENAME(Name)
                        FROM   sys.columns 
                        WHERE  object_id = Object_id(@Table)
                        -- concatenate result strings with FOR XML PATH
                        FOR XML PATH ('')), 1, 7, '');
    
    EXECUTE sp_executesql @SQL;
    

    Which will produce SQL Like the following for a table with two columns (Column1 and Column2)

    SELECT 'Column1' AS [Column], 
            CAST([Column1] AS NVARCHAR(MAX)) AS [ColumnValue], 
            COUNT(*) AS [Count] 
    FROM    [TableName] 
    GROUP BY [Column1] 
    UNION 
    SELECT  'Column2' AS [Column], 
            CAST([Column2] AS NVARCHAR(MAX)) AS [ColumnValue], 
            COUNT(*) AS [Count] 
    FROM    [TableName] 
    GROUP BY [Column2]
    

    EDIT

    If you want a new result set for each column then use:

    DECLARE @Table SYSNAME = 'TableName'; 
    DECLARE @SQL NVARCHAR(MAX) = '';
    SELECT @SQL = (SELECT ' SELECT ' + QUOTENAME(Name) 
                            + ', COUNT(*) AS [Count] FROM ' 
                            + QUOTENAME(@Table) + ' GROUP BY ' + QUOTENAME(Name) + ';'
                    FROM   sys.columns 
                    WHERE  object_id = Object_id(@Table)
                    -- concatenate result strings with FOR XML PATH
                    FOR XML PATH (''));
    
    EXECUTE sp_executesql @SQL;
    

    Which would produce SQL Like:

    SELECT  [Column1], 
            COUNT(*) AS [Count] 
    FROM    [callsupplier] 
    GROUP BY [Column1];
    
    SELECT  [Column2], 
            COUNT(*) AS [Count] 
    FROM    [callsupplier] 
    GROUP BY [Column2];
    

提交回复
热议问题