简体   繁体   中英

MYSQL COUNTING RIGHT ANSWERS WITH 3 TABLES (USER - ANSWERS - QUESTIONS)

I have 3 tables:

USER:

  • USERID
  • NAME
  • COMPANY
  • AGE

QUESTIONS:

  • SETID (IDENTIFY ALL QUESTION FROM THE SAME GROUP)
  • QUESTIONID
  • QUESTION (like "Who is the USA's President?")
  • ANSWER "A"
  • ANSWER "B"
  • ANSWER "C"
  • ANSWER "D"
  • CORRECT ANSWER (as CA)

ANSWERS:

  • USERID
  • ANSWERFORQUESTION1 (as AFQ1)
  • ANSWERFORQUESTION2 (as AFQ2)
  • ANSWERFORQUESTION3... (Will be 20 Questions)
  • LAST ANSWER (as LA) <<< I use this to know what is the last answer of each user and post the next answer to him.. (IF 21 = "ALL DONE!")

I have 2 issues:

1-I Need to count the % of "Correct Answers" for each Answer.

2-I Need to count the % of "Correct Answers" for each Answer - for COMPANY "A", COMPANY "B"... (will be 5 companies)

TO SOLVE ISSUE 1:

select 
    count(DISTINCT ANSWERS.USERID) as TOTAL,

    sum(case when ANSWERS.AFQ1 = QUESTIONS.CA AND ANSWERS.LA = 21 AND QUESTIONS.QUESTIONID = 1 then 1 else 0 end) AT1,
    sum(case when ANSWERS.AFQ2 = QUESTIONS.CA AND ANSWERS.LA = 21 AND QUESTIONS.QUESTIONID = 2 then 1 else 0 end) AT2,

   (....until 20)

from ANSWERS, QUESTIONS
Where ANSWERS.LA = 21

With this I got a Table with TOTAL ANSWERS (COMPLETED = 21) - AND AT1, AT2, AT3.. with each total "correct answers" for each answer.

Then I can do a AT1/TOTAL to get all %.

Issue 1 is ok.

But how I can do the same for Issue 2?

tks!

 select 
        COMPANY,count(DISTINCT ANSWERS.USERID) as TOTAL,

        sum(case when ANSWERS.AFQ1 = QUESTIONS.CA AND ANSWERS.LA = 21 AND QUESTIONS.QUESTIONID = 1 then 1 else 0 end) AT1,
        sum(case when ANSWERS.AFQ2 = QUESTIONS.CA AND ANSWERS.LA = 21 AND QUESTIONS.QUESTIONID = 2 then 1 else 0 end) AT2,

       (....until 20)

  from ANSWERS a, QUESTIONS
  join user u on u.userid = a.userid 
  Where ANSWERS.LA = 21
  group by u.COMPANY

Hint 1: join with USER table on Answer.Userid = User.userid

Hint 2: use GROUP BY for COMPANY

Note : My syntax may be wrong. I have used SQL server syntax.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM