2010-05-28 76 views
0

幫助基於下表上用T-SQL數據聚合

Area S1 S2 S3 S4 
-------------------- 
A1 5 10 20 0 
A2 11 19 15 20 
A3 0 0 0 20 

我要生成的輸出,這將使沒有「0」的列數。

所以輸出將

Area S1 S2 S3 S4 Count 
------------------------- 
A1 5 10 20 0 3 
A2 11 19 15 20 4 
A3 0 0 0 20 1 

回答

6

一種方法是添加case語句的結果一起:

select area, s1, s2, s3, s4, 
    case when S1 <> 0 then 1 else 0 end + 
    case when S2 <> 0 then 1 else 0 end + 
    case when S3 <> 0 then 1 else 0 end + 
    case when S4 <> 0 then 1 else 0 end as Count 
from YourTable 
0

只是爲了讓你的思想,你也可以做到這一點與加盟:

SELECT t1.*, COUNT(t2.Area) AS Count 
FROM Table t1 
LEFT JOIN Table t2 
ON t2.Area = t1.Area AND (t2.S1 <> 0 OR t2.S2 <> 0 OR t2.S3 <> 0 OR t2.S4 <> 0) 
GROUP BY Area 
ORDER BY Area