开发者

help with t-sql data aggregation

Based on the following table

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

I want to generate an output that will give the number开发者_JS百科 of columns not having "0".

So the output would be

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


One way would be to add the result of case statements together:

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


Just to get you thinking, you could also do this with a join:

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜