mysql - Getting percentages from sql query and grouping -
so i'm have database holds survey questions , wanting run special query don't know how it. things note: there can 2-6 answers per question depending on question.
these tables i'm using , example data:
table: answers_only table: questions_only ╔════════════════╦═══════════╗ ╔═════════════════╦════════════════════════════╗ ║ answer_id (pk) ║ answer ║ ║question_id (pk) ║ question ║ ╠════════════════╬═══════════╣ ╠═════════════════╬════════════════════════════╣ ║ 65114 ║ yes ║ ║ 123 ║ happy? ║ ║ 614 ║ no ║ ║ 1967 ║ think you're smart? ║ ║ 23 ║ ║ ╚═════════════════╩════════════════════════════╝ ╚════════════════╩═══════════╝ table: questions ╔════════════════╦══════════════════╦════════════════╦════════════════╗ ║ unique_id (pk) ║ question_id (fk) ║ answer_id (fk) ║ person_id (fk) ║ ╠════════════════╬══════════════════╬════════════════╬════════════════╣ ║ 1 ║ 123 ║ 65114 ║ 5521 ║ ║ 2 ║ 123 ║ 614 ║ 2511 ║ ║ 3 ║ 1967 ║ 614 ║ 2511 ║ ╚════════════════╩══════════════════╩════════════════╩════════════════╝
so have table questions contains ids (fk) questions_only holds actual questions.
what i'm trying top percentage of question , order , above 90% (query). so...let's had 100 people asked 'are happy?' question. 5% said no , 95% said yes. because it's 95%, it'd show in query. on other hand, if 20% answered no on 'you think you're smart?' question , 80% said yes doesn't show up. think need next bunch of sub queries i'm not sure. here have...but know i'm way off. appreciated.
select question, answer, round(count(*)/(select count(*) questions inner join questions_only on questions_only.question_id=questions.question_id)*100) 'percent' questions inner join answers_only on answers_only.answer_id=questions.answer_id inner join questions_only on questions_only.question_id=questions.question_id group answer order count(*) desc
the end goal here find out questions easy answers, majority in favor of.
wanted results query ╔═══════════════════════════════╦══════════════════╦════════════════╗ ║ question ║ answer ║ percent ║ ╠═══════════════════════════════╬══════════════════╬════════════════╬ ║ happy? ║ yes ║ 97 ║ ║ think you're smart? ║ yes ║ 96 ║ ║ 1-5 how exciting surfing? ║ 5 ║ 92 ║ ╚═══════════════════════════════╩══════════════════╩════════════════╝
you should make subquery count of answers each question , join questions table:
select max(questions_only.question), max(answers_only.answer), (count(*)/max(t.all_count))*100 answer_percent questions join ( select question_id, count(*) all_count questions group question_id ) t on questions.question_id=t.question_id join questions_only on questions.question_id=questions_only.question_id join answers_only on questions.answer_id=answers_only.answer_id group questions.question_id,questions.answer_id having (count(*)/max(t.all_count))*100>=90
Comments
Post a Comment