Quiero usar el máximo y contar las funciones agregadas juntas en la consulta de mysql

I am using mysql 5.0.51b. I have one table named xyz. xyz table has a columns abc,location,pqr and lmn Everytime an information is sent to particular location, its entry is done in xyz table. I want to have the name of the location to which maximum information is sent.

The way i tried: First of all i count the number of entries sent to each location using count and group by. Now, the problem is to have the name(s) of the location with maximum values.

I have used temporary solution: I use order by clause and limit to get the first record that has max values. But this has one problem If two locations has same count then above solution will give only one location and the other with same count will not be returned.

I want to solve this problem Any hint will be very helpful Thanks in anticipation

preguntado el 08 de noviembre de 11 a las 11:11

4 Respuestas

Thank you very much to everyone who has responded to my question and spared time to solve my problem.

However, i have got the solution:

SELECT count( * ) AS cnt2, location
FROM sms
GROUP BY location
HAVING cnt2 = (
SELECT count( * ) AS cnt
FROM sms
GROUP BY location
ORDER BY cnt DESC
LIMIT 1 );

very important hint on http://lists.mysql.com/mysql/203074

The inner query gives you the max count and outer query compares each count with max count.

respondido 10 nov., 11:17

Wonderful! Don't forget to vote on the responses that you found useful. This expresses your thanks in a meaningful way which encourages people to continue to respond to your future requests. If there is no response that directly answers your question, it is possible to accept your own answer after a couple of days. Accepting an answer helps other people find it when searching for similar questions. Welcome to Stack Overflow! - T.Rob

Select MAX(cnt.Total) from
(select count( Name)as Total from Gk_RegUser_answer_rel group by Reg_UserId) As cnt 

Respondido el 20 de diciembre de 11 a las 15:12

Try this interesting solution -

SELECT x.* FROM xyz x
  JOIN (
    SELECT GROUP_CONCAT(location) locations FROM (
      SELECT location, COUNT(*) cnt FROM xyz GROUP BY location ORDER BY COUNT(*)) t
    GROUP BY cnt DESC
    LIMIT 1
      ) t
  ON FIND_IN_SET(x.location, t.locations);

respondido 08 nov., 11:15

SELECT COUNT(*), `location` FROM `xyz` GROUP BY `location`

Above query will give you the information count to a specific location.

If this is not what you were looking for, can you provide some sample data and expected output?

respondido 08 nov., 11:15

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.