SQL count specific value over multiple columns and rows

后端 未结 5 1173
甜味超标
甜味超标 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.

提交回复
热议问题