获得最大出现次数以及group by中的count

时间:2014-04-26 05:14:08

标签: mysql

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

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

给出Invalid use of group function错误。

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

3 个答案:

答案 0 :(得分:0)

试试这个

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

<强> OP:


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

答案 1 :(得分:0)

我通过查看您的sqlfiddle数据更新了我的查询。请立即尝试:

create table tableA(question_id int,response varchar(50));

insert into tableA values(1,'yes'),(1,'yes'),(2,'agree'),(1,'no'),(3,'disagree'),(2,'agree'),(2,'disagree');

SELECT question_id,
       max(response) AS max_response,
(select count(response) from tableA b where a.response= b.response and a.question_id= b.question_id ) as max_response_count,
       count(*) AS count_response

FROM tableA a
GROUP BY question_id

我试着按预期得到结果..

答案 2 :(得分:0)

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