所以我目前有一个数据库可以存储调查问题,我现在想要运行一个特殊查询,但不知道该怎么做。 需要注意的事项:根据问题,每个问题可以有2-6个答案。
这些是我使用的表格以及一些示例数据:
Table: answers_only Table: questions_only
╔════════════════╦═══════════╗ ╔═════════════════╦════════════════════════════╗
║ answer_ID (PK) ║ answer ║ ║question_ID (PK) ║ question ║
╠════════════════╬═══════════╣ ╠═════════════════╬════════════════════════════╣
║ 65114 ║ yes ║ ║ 123 ║ Are you happy? ║
║ 614 ║ no ║ ║ 1967 ║ You think you're smart? ║
║ 23 ║ sometimes ║ ╚═════════════════╩════════════════════════════╝
╚════════════════╩═══════════╝
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 ║
╚════════════════╩══════════════════╩════════════════╩════════════════╝
所以我有一个表格问题,其中包含 questions_only 的ID(FK),其中包含实际问题。
我想要获得的是一个问题的最高百分比,然后按此顺序获得超过90%(查询)的任何内容。所以......让我们说有100个人被问到“你快乐吗?'题。 5%表示否,95%表示是。因为它是95%,它会出现在查询中。另一方面,如果20%的人回答没有,你认为自己聪明吗?'问题,80%表示是,然后它就不会显示出来。我想我需要接下来一堆子查询,但我不确定。这就是我所拥有的......但我知道我已经走了。任何帮助将不胜感激。
SELECT question, answer, round(COUNT(*)/(select count(*) from questions
INNER JOIN questions_only on questions_only.question_ID=questions.question_ID)*100) AS
'Percent' FROM 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 BY answer order by COUNT(*) DESC
这里的最终目标是找出所有容易回答的问题,大多数人都赞成。
wanted results from query
╔═══════════════════════════════╦══════════════════╦════════════════╗
║ question ║ answer ║ Percent ║
╠═══════════════════════════════╬══════════════════╬════════════════╬
║ Are you happy? ║ Yes ║ 97 ║
║ You think you're smart? ║ Yes ║ 96 ║
║ 1-5 How exciting is surfing? ║ 5 ║ 92 ║
╚═══════════════════════════════╩══════════════════╩════════════════╝
答案 0 :(得分:1)
您应该为每个问题创建一个包含详细答案的子查询,并将其与您的QUESTIONS表联系起来:
SELECT MAX(questions_only.question),
MAX(answers_only.answer),
(COUNT(*)/MAX(t.all_count))*100 as answer_percent
FROM questions
JOIN (
SELECT question_id,
COUNT(*) as all_count
FROM questions
GROUP BY question_id
) as 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 BY questions.question_ID,questions.answer_ID
HAVING (COUNT(*)/MAX(t.all_count))*100>=90
答案 1 :(得分:0)
我没有在工作室检查这个,但它应该给你一种方法。
select question, answer, round((c/c1)*100) from
(select question, answer, count (*) c1, c from
questions q
join questions_only qo on q.question_ID = qo.question_ID
join answers a on q.answer_ID = a.answer_ID
join (select question_ID, count(*) c fromquestions )
as q1 on q.question_ID = q1.question_ID
Group by question, answer)
as table