0

There is two table Questions and Answer. Question contains 65 questions(other means 65 rows) consist of quiestionid and correcAnswer of question. Answer table contains answers of users and userId

My manager asked me to build such a query that should tell us; for each question how many true answer and false answer. percentage of true answers over total answers(trueAnswerCount/answersCount)

There is some others, i handled them but the ones above are tough, this is how I tried so far;

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;

this gives me the result below: enter image description here

From the result above all I need total true count and false count for each QuestionNo, userid Tells me only when new 65 rows of question belongs to new user so I don't need it but it's creepy how can I achieve this?

2 Answers 2

2

following SqlZim answer you need the aggregation by 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
Sign up to request clarification or add additional context in comments.

6 Comments

Aaand can you helpme find ratio of these true and false count for each question. I added this for another column but now work; ", (100* TrueCount/FalseCount) as ratio"
dont take negative votes to seriously. You have to live with them, just accept it and move on.
Yeah thanks Juan I am here because there is more like you here than like them.
You cant use the alias, you have to write the formula again. Check edit for example.
You can use 100 * avg(case when UserAnswer = CorrectAnswer then 1.0 else 0.0 end) instead of dealing with the division and count(*)
|
1

using conditional aggregation:

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;

3 Comments

You forgot the aggregation for question.
@JuanCarlosOropeza I think you are right can you provide details, thanks
@JuanCarlosOropeza Ack, that's what I get for getting called away.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.