Reputation: 401
I created a survey/polling application and after a user answers a given question I want to display the total responses for the question they answered.
I am trying to aggregate the responses of a specific quetsion with COUNT
(I will have the question_id
stored in the session variable of Flask).
database schema and instance data
I want to combine the output of these two queries into a single query, where the count of the result is paired up with the corresponding choice text:
-- Displays text of choices
SELECT choice.text
FROM choice
WHERE question_id = 12;
-- Displays how many times the question was answered with a choice
SELECT count(*)
FROM answer
WHERE question_id = 12
GROUP BY choice_id;
These are all of my failed attempts. I will change 12 to a dynamic variable in the application, this was just for testing.
SELECT COUNT(a.choice_id), c.text
FROM answer AS a, question AS q, choice AS C
WHERE a.question_id = q.question_id
GROUP BY c.choice_id;
SELECT COUNT(a.choice_id)
FROM answer AS a, question AS q
WHERE a.question_id = 12
GROUP BY a.choice_id;
SELECT COUNT(a.choice_id), c.text
FROM answer AS a, question AS q, choice AS c
WHERE a.question_id = q.question_id AND a.question_id = c.question_id
GROUP BY a.choice_id;
SELECT *
FROM choice AS c
WHERE c.question_id in (
SELECT COUNT(a.choice_id)
FROM answer AS a, question AS q
WHERE a.question_id = 12 --VARIABLE DATA FOR QUESTION
GROUP BY a.choice_id
);
SELECT DISTINCT(q.text)
FROM answer AS a, question AS q
WHERE a.question_id = 12;
SELECT COUNT(c.choice), c.text,
FROM choice AS c, answer AS a
WHERE c.question_id = 12
GROUP BY c.choice;
SELECT COUNT(choice.choice_id)
FROM choice, answer
WHERE answer.question_id = 12
GROUP BY choice.choice;
Upvotes: 0
Views: 131
Reputation: 338
If your question is that( total number of times the question is answered based on each option), for example
Q1 is answered 2 times with choice 1. Q1 is answered 5 times with choice 4. Q1 is answered 4 times with choice 2. Q1 is answered 3 times with choice 3.
Well, here is the answer
SELECT
NAME AS question_name,
cname AS choice_name,
COUNT(id) AS total_count
FROM
answer AS a,
question AS q,
choice AS c
WHERE
a.qid = q.id and a.cid=c.cid and a.qid = 1
GROUP BY
a.cid
Sceenshot
Upvotes: 1