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

前端 未结 3 1872
庸人自扰
庸人自扰 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 21:01

    This version makes a good snippet:

    DECLARE @sql NVARCHAR(MAX) = N'';
    
    SELECT @sql += 'SELECT ''' + t.name + ''', ''' + c.name + ''', ' + c.name + ', COUNT(' + c.name + ') AS C FROM ' + QUOTENAME(s.name) + '.' + QUOTENAME(t.name) + ' GROUP BY ' + c.name + ';' + CHAR(13)
        FROM sys.tables AS t
        INNER join sys.columns c on t.object_id = c.object_id
        INNER JOIN sys.schemas AS s ON t.[schema_id] = s.[schema_id] 
        WHERE s.name LIKE 'stage' AND t.name LIKE 'table' AND c.name LIKE '%whatever%';
    
    --PRINT @sql;
    EXEC sp_executesql @sql
    

提交回复
热议问题