要獲取需要的數據,您需要取消數據轉移。下面是使用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)
你試過了什麼?請添加您的代碼。 –