简体   繁体   中英

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 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM