Sql 在多个列/行中计算值的实例(例如,';4';)

Sql 在多个列/行中计算值的实例(例如,';4';),sql,sql-server,count,Sql,Sql Server,Count,我在SQL数据库中得到了调查结果。分数是1-5分 数据表的当前格式如下: Survey_id, Question_1, Question_2, Question_3 383838, 1,1,1 392384, 1,5,4 393894, 4,3,5 我正在运行一个需要%4、%5的新查询。。。问题不重要,只是总体而言 乍一看,我在想 sum(iif(Question_1 =5,1,0)) + sum(iif(Question_2=5,1,0)) .... as total5s sum(iif(Q

我在SQL数据库中得到了调查结果。分数是1-5分

数据表的当前格式如下:

Survey_id, Question_1, Question_2, Question_3
383838, 1,1,1
392384, 1,5,4
393894, 4,3,5
我正在运行一个需要%4、%5的新查询。。。问题不重要,只是总体而言

乍一看,我在想

sum(iif(Question_1 =5,1,0)) + sum(iif(Question_2=5,1,0)) .... as total5s
sum(iif(Question_1=4,1,0)) + sum(iif(Question_2=4,1,0)) .... as total4s
但我不确定这是实现这一目标的最快或最优雅的方式

编辑:嗯,在第一次测试时,此查询似乎已无法正常工作


EDIT2:我想我需要的是sum,而不是count。在我的示例中,will edit。

您必须取消数据绑定,然后计算%的响应。由于问题数量有限,您可以使用
union-all
取消对数据的抽取

select 100.0*count(case when question=4 then 1 end)/count(*) as pct_4s
from (select survey_id,question_1 as question from tablename 
      union all
      select survey_id,question_2 from tablename 
      union all
      select survey_id,question_3 from tablename 
      ) responses
另一种方法是

select 100.0*(count(case when question_1=4 then 1 end)
              +count(case when question_2=4 then 1 end)
              +count(case when question_3=4 then 1 end))
       /(3*count(*))
from tablename
使用@Dudu建议的
unpivot

with unpivoted as (select *
                   from tablename
                   unpivot (response for question in (question_1,question_2,question_3)) u
                   )
select 100.0*count(case when response=4 then 1 end)/count(*)
from unpivoted

对于unpivot,我建议
unpivot
/
cross apply
认为您已经掌握了一些东西,但我认为需要使用sum()而不是潜在的计数(计数取0为1),并且可能使用unpivot函数,嗯,谢谢您的想法。@user45867-注意计数超过1/null,而不是1/0@user45867 .. count将
null
赋值给除4以外的值(在本例中),这些值不会被计数
sum(case when..then 1 else 0 end)
将给出相同的结果。