有两个表问题和答案。问题包含65个问题(其他表示65行)包含quiestionid和correcAnswer的问题。答案表包含用户和userId的答案
我的经理让我建立一个应该告诉我们的问题; 对于每个问题,有多少真实答案和错误答案。 真实答案占总答案的百分比(trueAnswerCount / answersCount)
还有其他一些,我处理过它们但是上面的那些很难,这就是我到目前为止的尝试;
select SoruId as QuestionID, userId, UserAnswer, oss.CorrectAnswer,
case
When UserAnswer = CorrectAnswer Then 'TRUE'
else 'FALSE'
end
from OnlineSinav.Cevap osc
join OnlineSinav.Soru oss on osc.SoruId=oss.ID;
从上面的结果我需要每个QuestionNo的总真实计数和错误计数,userid告诉我只有当新的65行问题属于新用户时所以我不需要它,但它令人毛骨悚然我怎么能实现这一点?
答案 0 :(得分:2)
在SqlZim回答后,您需要通过QuestionNo
进行聚合select
QuestionNo = osc.SoruId
, TrueCount = sum(case when UserAnswer = CorrectAnswer then 1 else 0 end)
, FalseCount = sum(case when UserAnswer = CorrectAnswer then 0 else 1 end)
, TruePercent = 100.0 * avg(case when UserAnswer = CorrectAnswer then 1.0 else 0.0 end)
, FalsePercent = 100.0 * avg(case when UserAnswer = CorrectAnswer then 0.0 else 1.0 end)
from OnlineSinav.Cevap osc
inner join OnlineSinav.Soru oss
on osc.SoruId=oss.ID
group by osc.SoruId
答案 1 :(得分:1)
使用条件聚合:
select
TrueCount = sum(case when UserAnswer = CorrectAnswer then 1 else 0 end)
, FalseCount = sum(case when UserAnswer = CorrectAnswer then 0 else 1 end)
from OnlineSinav.Cevap osc
inner join OnlineSinav.Soru oss
on osc.SoruId=oss.ID;