gpt4 book ai didi

sql - 如何在SQL中计算一条记录中具有空值的所有字段?

转载 作者:行者123 更新时间:2023-12-04 16:29:48 28 4
gpt4 key购买 nike

有没有办法计算除 PrimaryKey 列之外的特定记录的所有具有空值的字段?

Example:

ID Name Age City Zip

1 Alex 32 Miami NULL
2 NULL 24 NULL NULL

作为输出,我需要得到 1 和 3。没有明确指定列名。

最佳答案

declare @T table
(
ID int,
Name varchar(10),
Age int,
City varchar(10),
Zip varchar(10)
)

insert into @T values
(1, 'Alex', 32, 'Miami', NULL),
(2, NULL, 24, NULL, NULL)

;with xmlnamespaces('http://www.w3.org/2001/XMLSchema-instance' as ns)
select ID,
(
select *
from @T as T2
where T1.ID = T2.ID
for xml path('row'), elements xsinil, type
).value('count(/row/*[@ns:nil = "true"])', 'int') as NullCount
from @T as T1

结果:
ID          NullCount
----------- -----------
1 1
2 3

更新:

这是一个更好的版本。感谢 Martin Smith .
;with xmlnamespaces('http://www.w3.org/2001/XMLSchema-instance' as ns)
select ID,
(
select T1.*
for xml path('row'), elements xsinil, type
).value('count(/row/*[@ns:nil = "true"])', 'int') as NullCount
from @T as T1

更新:

并使用更快的 XQuery 表达式。
;with xmlnamespaces('http://www.w3.org/2001/XMLSchema-instance' as ns)
select ID,
(
select T1.*
for xml path('row'), elements xsinil, type
).value('count(//*/@ns:nil)', 'int') as NullCount
from @T as T1

关于sql - 如何在SQL中计算一条记录中具有空值的所有字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9079037/

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