简体   繁体   English

MySql查询次数和区别

[英]MySql query count and distinct

I have a table 'questions' with columns 我有一个带有列的表格“问题”
userid 用户身份
qid(question id) qid(问题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. 问题100可能有4个答案可供选择。
question 200 might have 6 answers to choose from. 问题200可能有6个答案可供选择。
question 300 might have 2 answers to choose from. 问题300可能有2个答案可供选择。
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 我想知道问题100给出的答案最多的计数是多少,问题100的第二高答案的计数是多少,问题100的第三高答案的计数是多少,等等。

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. 按问题分组,然后可以使用适用于每个组的聚合函数,例如sum() And you can use a condition in sum() to do conditional summing 您可以在sum()使用条件进行条件求和

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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