Is there a simpler way to find MODE(S) of some values in MySQL

前端 未结 1 1629
傲寒
傲寒 2020-12-11 07:15

MODE is the value that occurs the MOST times in the data, there can be ONE MODE or MANY MODES

here\'s some values in two tables (sqlFiddle)

create ta         


        
相关标签:
1条回答
  • 2020-12-11 08:02

    You are very close with the last query. The following finds one mode:

    SELECT value, occurs
    FROM (SELECT value,count(*) as occurs
          FROM t200
          GROUP BY `value`
          LIMIT 1
         ) T1
    

    I think your question was about multiple modes, though:

    SELECT value, occurs
    FROM (SELECT value, count(*) as occurs
          FROM t200
          GROUP BY `value`
         ) T1
    WHERE occurs = (select max(occurs)
                    from (select `value`, count(*) as occurs
                          from t200
                          group by `value`
                         ) t
                   );
    

    EDIT:

    This is much easier in almost any other database. MySQL supports neither with nor window/analytic functions.

    Your query (shown below) does not do what you think it is doing:

      SELECT value, occurs  
      FROM (SELECT value, count(*) as occurs
            FROM t200
            GROUP BY `value`
           ) T1
      HAVING occurs = max(occurs) ; 
    

    The final having clause refers to the variable occurs but does use max(occurs). Because of the use of max(occurs) this is an aggregation query that returns one row, summarizing all rows from the subquery.

    The variable occurs is not using for grouping. So, what value does MySQL use? It uses an arbitrary value from one of the rows in the subquery. This arbitrary value might match, or it might not. But, the value only comes from one row. There is no iteration over it.

    0 讨论(0)
提交回复
热议问题