gpt4 book ai didi

mysql - 获取最大出现次数以及分组依据中的计数

转载 作者:行者123 更新时间:2023-11-30 23:02:36 25 4
gpt4 key购买 nike

我有一个看起来像这样的表

question_id   response
1 yes
1 yes
2 agree
1 no
3 disagree
2 agree
2 disagree

我希望我的查询返回

question_id      max_response     max_response_count   total_responses
1 yes 2 3
2 agree 2 3
3 disagree 1 1

查询

SELECT question_id,
max(response),
count(max(response)),
count(*)
FROM response
GROUP BY question_id

给出 组函数的无效使用 错误。

我应该放置哪个查询以获得上述输出。

最佳答案

试试这个

SELECT T.question_id,Max(MR) max_response,MAX(CR)max_response_count,(Select Count(question_id) from response where question_id = T.question_id)total_responses
FROM
(SELECT question_id,max(response) MR,count(response) CR
FROM response group by question_id,response
)T
GROUP BY T.question_id

Fiddle Demo

操作:

    +--------------------------------------------------------------------+    |QUESTION_ID  | MAX_RESPONSE   | MAX_RESPONSE_COUNT |TOTAL_RESPONSES |    +--------------------------------------------------------------------+    |  1          |    yes         |        2           |       3        |    |  2          |    disagree    |        2           |       3        |    |  3          |    disagree    |        1           |       1        |    +--------------------------------------------------------------------+

关于mysql - 获取最大出现次数以及分组依据中的计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23306924/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com