Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/76.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
我不知道';当我从表SQL Server 2008中计算名称时,我不希望出现空值_Sql_Sql Server_Sql Server 2008_Group By_Union - Fatal编程技术网

我不知道';当我从表SQL Server 2008中计算名称时,我不希望出现空值

我不知道';当我从表SQL Server 2008中计算名称时,我不希望出现空值,sql,sql-server,sql-server-2008,group-by,union,Sql,Sql Server,Sql Server 2008,Group By,Union,期望输出: UserName | Person1 | Person2 | Person3 Kapil | Null | Null | Dks Kapil | Dks | AA | Null Kapil | SKS

期望输出:

UserName           |         Person1   |     Person2    |     Person3


Kapil              |         Null      |       Null     |     Dks


Kapil              |         Dks       |       AA       |     Null

Kapil              |         SKS       |       AA       |     Dks

我不想在输出中计算空值。有人能帮我吗?

要获取所需的数据,您需要取消填充数据。下面是一种使用
联合所有
的简单方法:

User_Name   Person    Count

Kapil       Dks       3

Kapil       SKS       1

Kapil       AA        2

Kapil       Null      0
如果根本不需要该行,请使用
where

select user_name, person, count(person)
from (select user_name, person1 as person from table t union all
      select user_name, person2 as person from table t union all
      select user_name, person3 as person from table t
     ) t
group by user_name, person;
但是,所需的输出表明您希望该行的计数为
0

编辑:

要计算非空值,有一种方法:

select user_name, person, count(*)
from (select user_name, person1 as person from table t union all
      select user_name, person2 as person from table t union all
      select user_name, person3 as person from table t
     ) t
where person is not null
group by user_name, person;
写这篇文章的更清晰的方式可能是:

select user_name, person, count(nullif(ltrim(rtrim(person)), '') )
from (select user_name, person1 as person from table t union all
      select user_name, person2 as person from table t union all
      select user_name, person3 as person from table t
     ) t
group by user_name, person;
试试这个:

select user_name, person, sum(case when ltrim(rtrim(person)) > '' then 1 else 0 end)

你试过什么?请添加您的代码。非常感谢Gordon。我得到了一个输出。但我发现的另一个问题是在我的表中,有些包含空白而不是Null。所以现在我得到了输出中的空行数。我怎样才能避免这样的空白值和它们的计数?????谢谢。我得到了输出。但我发现的另一个问题是在我的表中,有些包含空白而不是Null。所以现在我得到了输出中的空行数。我怎样才能避免在我的输出中出现这样的空白值和它们的计数?????天哪,太棒了。多谢萨哈什·沙阿。工作正常。非常感谢
SELECT User_Name, Person, COUNT(1) AS Count
FROM (SELECT User_Name, Person1 AS Person
      FROM tableA 
      UNION ALL 
      SELECT User_Name, Person2 AS Person
      FROM tableA 
      UNION ALL 
      SELECT User_Name, Person3 AS Person
      FROM tableA 
     ) AS A 
WHERE Person IS NOT NULL AND Person != ''
GROUP BY User_Name, Person;