SQL count specific value over multiple columns and rows

后端 未结 5 1171
甜味超标
甜味超标 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:07

    Not so easy, each column needs to be hard-coded. I'd try something using a CASE or DECODE.

    SELECT 
    SUM(
    CASE WHEN q1 = 1 THEN 1 ELSE 0 END +
    CASE WHEN q2 = 1 THEN 1 ELSE 0 END +
    CASE WHEN q3 = 1 THEN 1 ELSE 0 END +
    CASE WHEN q4 = 1 THEN 1 ELSE 0 END +
    CASE WHEN q5 = 1 THEN 1 ELSE 0 END +
    CASE WHEN q6 = 1 THEN 1 ELSE 0 END +
    CASE WHEN q7 = 1 THEN 1 ELSE 0 END)
    FROM table
    WHERE Company = 'abc'
    

    Using a SUM instead of a COUNT will allow the CASE statement to be SUMed.

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2021-01-18 07:26

    This is very weird assignment but:

    http://sqlfiddle.com/#!9/2e7aa/3

    SELECT SUM((q1='1')+(q2='1')+(q3='1')+(q4='1')+(q5='1')+(q6='1')+(q7='1')) 
    FROM table
    WHERE Company = 'abc'
    AND '1' IN (q1,q2,q3,q4,q5,q6,q7)
    
    0 讨论(0)
  • 2021-01-18 07:28
    SELECT SUM(
        IF(q1 = 1, 1, 0) +
        IF(q2 = 1, 1, 0) +
        IF(q3 = 1, 1, 0) +
        IF(q4 = 1, 1, 0) +
        IF(q5 = 1, 1, 0) +
        IF(q6 = 1, 1, 0) +
        IF(q7 = 1, 1, 0)
    )
    FROM table
    WHERE Company = 'abc'
    
    0 讨论(0)
  • 2021-01-18 07:31

    Use conditional COUNT

    SELECT COUNT(case when q1 = '1' then 1 end)  + 
           COUNT(case when q2 = '1' then 1 end)  + 
           COUNT(case when q3 = '1' then 1 end)  + 
           COUNT(case when q4 = '1' then 1 end)  + 
           COUNT(case when q5 = '1' then 1 end)  + 
           COUNT(case when q6 = '1' then 1 end)  + 
           COUNT(case when q7 = '1' then 1 end) as ones_total
    FROM table
    WHERE Company = 'abc'
    
    0 讨论(0)
提交回复
热议问题