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
我不想在我的输出中计算空值。任何人都可以帮助我???
答案 0 :(得分:1)
要获取所需数据,您需要取消数据。使用union all
:
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;
如果您根本不想要行,请使用where
:
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;
但是,您所需的输出表明您希望行数为0
。
编辑:
要计算非空白值,这里有一种方法:
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)
答案 1 :(得分:0)
试试这个:
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;