ID jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
13441 37 0 0 0 0 67 0 0 0 0 0 0
13555 37 0 97 0 0 0 0 0 0 0 0 0
15103 67 0 97 0 0 0 0 0 0 0 0 0
16019 37 0 97 0 0 0 0 0 0 37 67 97
12951 67 0 97 0 0 0 0 0 0 0 0 0
16351 37 0 37 67 0 0 0 0 0 0 37 67
13244 37 0 37 67 0 0 0 0 0 0 0 0
答案 0 :(得分:4)
apply
:,结果非常简单
select t.*, c.cnt37
from t outer apply
(select count(*) as cnt37
from (values (jan), (feb), (mar), (apr), (may), (jun), (jul), (aug), (sep), (oct), (nov), (dec)
) v(val)
where val = 37
) c;
答案 1 :(得分:3)
您可以使用UNPIVOT
:
SELECT ID, COUNT(*) AS cnt
FROM (
SELECT *
FROM mytable) AS src
UNPIVOT (col FOR mon IN ([Jan], [Feb], [Mar], [Apr], [May], [Jun],
[Jul], [Aug], [Sep], [Oct], [Nov], [Dec])) AS unpvt
WHERE col = 37
GROUP BY ID