SQL Server计算表的每列中的不同值的数量

scr*_*Owl 1 sql sql-server

我有一个约150列的表.我想找到count(distinct(colName))每列的内容,但我想知道是否有办法这样做而不实际输入每个列名.

理想情况下我会使用,count(distinct(*))但这不起作用.

还有其他建议吗?

编辑:

如果这是我的表:

  id         col1         col2        col3      ...
  01         10001       west         north  
  02         10001       west         south  
  03         10002       east         south  
  04         10002       west         north  
  05         10001       east         south  
  06         10003       west         north 
Run Code Online (Sandbox Code Playgroud)

我正在寻找这个输出

count(distinct(id))   count(distinct(col1))    count(distinct(col2))   count(distinct(col3))
       6                       3                    2                      2
Run Code Online (Sandbox Code Playgroud)

rs.*_*rs. 5

你可以这样做:

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)
Run Code Online (Sandbox Code Playgroud)