简体   繁体   中英

MySql query count and distinct

I have a table 'questions' with columns
userid
qid(question id)
answer

The questions are multiple choice so not every question has the same number of answers a user can choose from.
question 100 might have 4 answers to choose from.
question 200 might have 6 answers to choose from.
question 300 might have 2 answers to choose from.
etc
So the table might look something like this:

+-------- --+---------+--------+
| userid    |   qid   | answer |
+---- ------+---------+--------+
|    1      |  100    |   4    |
|    1      |  200    |   6    |
|    1      |  300    |   1    |
|    1      |  400    |   4    |
|    2      |  100    |   1    |
|    2      |  400    |   6    |
|    3      |  200    |   4    |
|    3      |  400    |   4    |
|    3      |  100    |   1    |
|    4      |  100    |   1    |
|    4      |  400    |   6    |
|    5      |  200    |   1    |
|    5      |  400    |   6    |
+-----------+---------+--------+

I want to know what's the count for the most given answer for question 100, what's the count for the second highest answer for question 100 , what's the count for the 3rd highest answer for question 100, etc

I've can't figure how to query this and not sure if this is possible. I would the results to be something like:

+------+----+----+----+----+----+----+----+
| qid  |ans1|ans2|ans3|ans4|ans5|ans6|ans7|
+------+----+----+----+----+----+----+----+
|  100 |  3 |  0 | 0  | 1  | 0  | 0  | 0  |
|  200 |  1 |  0 | 0  | 0  | 0  | 0  | 0  |
|  300 |  1 |  0 | 0  | 0  | 0  | 0  | 0  |
|  400 |  0 |  2 | 0  | 0  | 0  | 3  | 0  |
+------+----+----+----+----+----+----+----+

Group by the questions and then you can use aggregate functions like sum() that apply to each group. And you can use a condition in sum() to do conditional summing

select qid,
       sum(answer = 1) as ans1,
       sum(answer = 2) as ans2,
       sum(answer = 3) as ans3,
       sum(answer = 4) as ans4,
       sum(answer = 5) as ans5,
       sum(answer = 6) as ans6,
       sum(answer = 7) as ans7,
       count(*) as total
from your_table
group by qid

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