我想通过使用sql计算每个ID多少37个

时间:2016-06-14 13:46:07

标签: sql sql-server

   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

2 个答案:

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