帮助t-sql数据聚合

时间:2010-05-28 23:15:59

标签: sql sql-server tsql sql-server-2008

基于下表

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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