繁体   English   中英

SQL计算表中所有列的不同值和计数空值

[英]SQL count distinct values and count null values for all columns in a table

我有一个名为tbl_site的表,有50列。 我想编写一些SQL代码,它们将计算每列的不同值的数量和空值的数量,而不必为每列运行语句。

我理解这可能包括对information_schema.columns运行嵌套查询,但我不确定如何进一步构造查询。 如果可能,空值还包括''和''的值。

所需的输出如下:

Column      | Distinct | Null
site_id     | 100      | 0
sitearea_id | 12       | 0
site_area   | 54       | 5
etc....

尝试计算distinct和sum案例的混合:

SELECT Column, count(distinct Column) as 'Distinct'
,sum(case when Column is null then 1 else 0 end) as 'Null'
FROM  tbl_site
GROUP BY 1

是的,在我为SQL Server制作脚本之后,我注意到它是MySQL ...但无论如何这里是代码以防有人需要它......或者如果你从中得到它的想法怎么做

declare @position int = 1,
        @sql nvarchar(max),
        @columnCnt int,
        @currentColumn nvarchar(50),
        @TableName nvarchar(50) = 'YourTableName',
        @DBName nvarchar(50) = 'YourDbName';

if (OBJECT_ID('tempdb..#MyRowCount')) IS NOT NULL DROP TABLE #MyRowCount
CREATE TABLE #MyRowCount (ColumnName nvarchar(50), DistinctCount int, NullCount int)

set @columnCnt = (select MAX(ORDINAL_POSITION) from INFORMATION_SCHEMA.COLUMNS 
                  where TABLE_NAME = @TableName and TABLE_CATALOG = @DBName)

WHILE (@position <= @columnCnt)
BEGIN

    set @currentColumn = (select COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS 
                          where TABLE_NAME = @TableName and 
                                TABLE_CATALOG = @DBName and 
                                ORDINAL_POSITION = @position)

    set @sql = 'INSERT INTO #MyRowCount (ColumnName, DistinctCount, NullCount)
                  SELECT ''' + @currentColumn + ''', 
                 (SELECT COUNT(DISTINCT [' + @currentColumn + ']) FROM ' + @TableName + ' where [' + @currentColumn + '] IS NOT NULL), 
                 (SELECT COUNT(*) FROM ' + @TableName + ' where [' + @currentColumn + '] IS NULL)';

    -- print @sql;

    execute (@sql);

    set @position = @position + 1;

END

SELECT * FROM #MyRowCount

在MySQL中,您可以使用以下命令构造查询:

set @sql = '
select ''[column]'' as col, count(distinct "[column]"), sum("[column]" is null)
from [table] t
';

select group_concat(replace(replace(@sql, '[table]', table_name), '[column]', column_name) separator ' union all ')
from information_schema.columns
where table_name = ?;

这种方法的警告是你需要确保你的group_concat最大长度值足够长(默认值1024不会让你走得太远)。

然后,您可以复制查询以使用prepare / execute来运行它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM