SQL Server count number of distinct values in each column of a table

前端 未结 5 972
别跟我提以往
别跟我提以往 2020-12-10 10:06

I have a table with ~150 columns. I\'d like to find the count(distinct(colName)) for each column but am wondering if there\'s a way to do so without actually t

5条回答
  •  余生分开走
    2020-12-10 10:16

    You can do this:

    DECLARE @query varchar(max)
        SELECT @query = 
        'SELECT ' + SUBSTRING((SELECT ',' +'COUNT(DISTINCT(' + column_name + ')) 
                 As ' + column_name + ' '  
                 FROM information_schema.columns
                 WHERE 
                 table_name = 'table_name'
                 for xml path('')),2,200000)  +  'FROM table_name'
    
    PRINT(@query)
    

提交回复
热议问题