gpt4 book ai didi

sql - 计算SQL中每列中NULL值的数量

转载 作者:行者123 更新时间:2023-12-04 13:29:47 25 4
gpt4 key购买 nike

我正在尝试编写一个脚本,该脚本将显示每列中非空值的数量以及表中的总行数。

我找到了几种方法来做到这一点:

SELECT sum(case my_column when null then 1 else 0) "Null Values",
sum(case my_column when null then 0 else 1) "Non-Null Values"
FROM my_table;


SELECT count(*) FROM my_table WHERE my_column IS NULL 
UNION ALL
SELECT count(*) FROM my_table WHERE my_column IS NOT NULL

但是这些需要我手动输入每个列名。有没有办法对每列执行此操作而不列出它们?

最佳答案

您应该使用 execute :

DECLARE @t nvarchar(max)
SET @t = N'SELECT '

SELECT @t = @t + 'sum(case when ' + c.name + ' is null then 1 else 0 end) "Null Values for ' + c.name + '",
sum(case when ' + c.name + ' is null then 0 else 1 end) "Non-Null Values for ' + c.name + '",'
FROM sys.columns c
WHERE c.object_id = object_id('my_table');

SET @t = SUBSTRING(@t, 1, LEN(@t) - 1) + ' FROM my_table;'

EXEC sp_executesql @t

关于sql - 计算SQL中每列中NULL值的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24411159/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com