SQL count specific value over multiple columns and rows

后端 未结 5 1221
甜味超标
甜味超标 2021-01-18 06:35

I feel as if this should be quite easy, but can\'t seem to find a solution. Suppose I have the following table:

|--------||---||---||---||---||---||---||---|         


        
5条回答
  •  遇见更好的自我
    2021-01-18 07:08

    For reasons of efficiency I don't recommend actually using this approach; but for learning purposes here's another way you could have broken down the problem along the lines of the way you were thinking about it.

    select sum(c) as total_ones
    from
        (
        select count(*) c from table where q1 = 1 union all
        select count(*)   from table where q2 = 1 union all
        select count(*)   from table where q3 = 1 union all
        select count(*)   from table where q4 = 1 union all
        select count(*)   from table where q5 = 1 union all
        select count(*)   from table where q6 = 1 union all
        select count(*)   from table where q7 = 1
        ) t
    

提交回复
热议问题