用于获取调查所选答案百分比的SQL Server查询

时间:2016-04-26 06:22:13

标签: sql-server percentage

我在asp.net上做了一个调查。调查有三种类型,包含不同的问题。用户可以选择五个答案:

strongly agree(5), 
agree(4), 
neutral(3), 
disagree(2), 
strongly disagree(1)

我将以下列形式获得结果。

survey results in database

我希望以下列形式显示结果。

enter image description here

我的问题是SQL查询将从强烈的不同意见中获得每个选定答案的百分比,如上图所示。

1 个答案:

答案 0 :(得分:0)

这就是诀窍:

select sq.QuestionId,sq.QuestionText, count(ca.AnswerOptionScore) as TotalAnswered,

sum(case when ca.AnswerOptionScore=5 then 1 else 0 end) * 100/CONVERT(decimal(4,2), count(ca.AnswerOptionScore)) as 'StronglyAgreePercent',

sum(case when ca.AnswerOptionScore=4 then 1 else 0 end) * 100/CONVERT(decimal(4,2), count(ca.AnswerOptionScore)) as 'AgreePercent',

sum(case when ca.AnswerOptionScore=3 then 1 else 0 end) * 100/CONVERT(decimal(4,2), count(ca.AnswerOptionScore)) as 'NeutralPercent',

sum(case when ca.AnswerOptionScore=2 then 1 else 0 end) * 100/CONVERT(decimal(4,2), count(ca.AnswerOptionScore)) as 'DisagreePercent',

sum(case when ca.AnswerOptionScore=1 then 1 else 0 end) * 100/CONVERT(decimal(4,2), count(ca.AnswerOptionScore)) as 'StronglyDisagreePercent'

from Suvey_Completed_Answers ca

inner join Survey_Questions sq on sq.QuestionId = ca.QuestionID
 Where ca.SurveyId = 3

group by sq.QuestionText,sq.QuestionText,sq.QuestionId