2014-12-22 54 views
1
UserName   |   Person1 |  Person2 |  Person3 


Kapil    |   Null  |  Null  |  Dks 


Kapil    |   Dks  |  AA  |  Null 

Kapil    |   SKS  |  AA  |  Dks 

慾望輸出:我不希望NULL值當我數着名字從我的表的SQL Server 2008

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) 
+0

謝謝洛特戈登。我有一個輸出。但我發現的另一個問題是在我的表中有些包含空白而不是空值。所以現在我在我的輸出中獲得空白行數。我如何避免這樣的空白值和他們的計數????? – Kapil

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; 
+0

謝謝。我得到了輸出。但我發現的另一個問題是在我的表中有些包含空白而不是空值。所以現在我在我的輸出中獲得空白行數。我如何避免這樣的空白值和他們在我的輸出計數????? – Kapil

+1

OMG真棒。謝謝Lot Saharsh Shah。它的工作很好。非常感謝 – Kapil

+0

我可以解釋如何計數(1)在上表中工作嗎? – Kapil

相關問題