【问题标题】:SQL count distinct values and count null values for all columns in a tableSQL 计算表中所有列的不同值并计算空值
【发布时间】:2019-10-11 02:34:38
【问题描述】:
我有一个名为 tbl_site 的表,有 50 列。我想编写一些 SQL 代码来计算每列的不同值的数量和空值的数量,而不必为每列运行语句。
我知道这可能包括对 information_schema.columns 运行嵌套查询,但我不确定如何进一步构建查询。如果可能,null 值也将包括 '' 和 ' ' 的值。
所需的输出如下:
Column | Distinct | Null
site_id | 100 | 0
sitearea_id | 12 | 0
site_area | 54 | 5
etc....
【问题讨论】:
标签:
mysql
sql
multiple-columns
isnull
distinct-values
【解决方案1】:
尝试混合使用不同的计数和求和的情况:
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
【解决方案2】:
是的,在我为 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
【解决方案3】:
在 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 来运行它。