gpt4 book ai didi

sql - 查找所有列的空/空记录数

转载 作者:行者123 更新时间:2023-12-01 10:01:03 26 4
gpt4 key购买 nike

我有一个包含 40 列的表格。

我想编写一个查询,返回每列中空值的数量。

例子,

如果有A、B、C、D列

我想要的输出是:

 A|B|C|D
3|5|4|9

其中 3 是记录数: 其中 A 为空或 A = ''等等……

如有任何帮助,我们将不胜感激。我正在使用 MS SQL 2008 R2

最佳答案

试试这个 -

DECLARE @temp TABLE
(
A VARCHAR(50)
, B VARCHAR(50)
, C VARCHAR(50)
, D VARCHAR(50)
)

INSERT INTO @temp (A, B, C, D)
VALUES
('', 'dr', '1', NULL),
('d', NULL, '45', 'h')

SELECT
A = COUNT(CASE WHEN ISNULL(A, '') = '' THEN 1 END)
, B = COUNT(CASE WHEN ISNULL(B, '') = '' THEN 1 END)
, C = COUNT(CASE WHEN ISNULL(C, '') = '' THEN 1 END)
, D = COUNT(CASE WHEN ISNULL(D, '') = '' THEN 1 END)
FROM @temp

更新:

在这种情况下,试试动态sql——

DECLARE @TableName SYSNAME
SELECT @TableName = 'dbo.test1'

DECLARE @SQL NVARCHAR(MAX)

SELECT @SQL = 'SELECT' + CHAR(13) + STUFF((
SELECT CHAR(13) + ', ' + c.name + ' = COUNT(CASE WHEN ISNULL(CAST(' + c.name + ' AS NVARCHAR(MAX)), '''') = '''' THEN 1 END)'
FROM (
SELECT o.[object_id]
FROM sys.objects o
JOIN sys.schemas s ON o.[schema_id] = s.[schema_id]
WHERE o.[type] = 'U'
AND s.name + '.' + o.name = @TableName
) o
JOIN sys.columns c ON o.[object_id] = c.[object_id]
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 2, ' ') + CHAR(13) + 'FROM ' + @TableName

PRINT @SQL

EXEC sys.sp_executesql @SQL

在输出中你可以得到类似的东西:

SELECT
WorkOutID = COUNT(CASE WHEN ISNULL(CAST(WorkOutID AS NVARCHAR(MAX)), '') = '' THEN 1 END)
, TimeSheetDate = COUNT(CASE WHEN ISNULL(CAST(TimeSheetDate AS NVARCHAR(MAX)), '') = '' THEN 1 END)
, DateOut = COUNT(CASE WHEN ISNULL(CAST(DateOut AS NVARCHAR(MAX)), '') = '' THEN 1 END)
, EmployeeID = COUNT(CASE WHEN ISNULL(CAST(EmployeeID AS NVARCHAR(MAX)), '') = '' THEN 1 END)
, IsMainWorkPlace = COUNT(CASE WHEN ISNULL(CAST(IsMainWorkPlace AS NVARCHAR(MAX)), '') = '' THEN 1 END)
, DepartmentUID = COUNT(CASE WHEN ISNULL(CAST(DepartmentUID AS NVARCHAR(MAX)), '') = '' THEN 1 END)
, WorkPlaceUID = COUNT(CASE WHEN ISNULL(CAST(WorkPlaceUID AS NVARCHAR(MAX)), '') = '' THEN 1 END)
, WorkShiftCD = COUNT(CASE WHEN ISNULL(CAST(WorkShiftCD AS NVARCHAR(MAX)), '') = '' THEN 1 END)
, TeamUID = COUNT(CASE WHEN ISNULL(CAST(TeamUID AS NVARCHAR(MAX)), '') = '' THEN 1 END)
, WorkHours = COUNT(CASE WHEN ISNULL(CAST(WorkHours AS NVARCHAR(MAX)), '') = '' THEN 1 END)
, AbsenceCode = COUNT(CASE WHEN ISNULL(CAST(AbsenceCode AS NVARCHAR(MAX)), '') = '' THEN 1 END)
, PaymentType = COUNT(CASE WHEN ISNULL(CAST(PaymentType AS NVARCHAR(MAX)), '') = '' THEN 1 END)
FROM dbo.test1

proff

关于sql - 查找所有列的空/空记录数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16165528/

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