简体   繁体   中英

Count group by using mysql

I'm trying to make some kind of "top" for some game stadistics

Table it's like this

mapname     authid  country     name    time    date    weapon  server

I've got this query, i think it's fine (lowest time per map it's shown)

SELECT name, min( time ) AS time
FROM kz_pro15
GROUP BY mapname ASC

and i'm getting results as

name    time
Santaaa     907.75
Zimmek*     184.82
:d  34.35
waldoo  1.04
Epiphany    8.54
Lovvon  185.51
Epiphany    64.53
menqz   73.67
waldoo  93.97
KoLkkE  207.83
q[o__o]p    78.35
Ulysses gc     T! CS    154.01
sasuke FTW  151.17
sasuke FTW  41.62
Santaaa     80.38
Santaaa     196.95
JonyBu  135.56
tiBU    93.12
Santaaa     122.04
Santaaa     36.08
EzzeqL  149.14
Zeqqe   106.75
bondiO^     110.68
INJUNABLES  102.09
Sublime     72.15
Player  106.11
=(M4t1ttU)=     158.95
foo conscience  80.98
gabe    27.21
gabe    58.5

But now i'm trying to count that results, to get how many records does players listed before has

gabe      2
sublime   1
player   13
SELECT name, count(*)
FROM (
 SELECT name, min( time ) AS time
 FROM kz_pro15
 GROUP BY mapname ASC 
) AS x
GROUP BY name

Unless name depends on mapname , your query is not correct:

SELECT name, min( time ) AS time
FROM kz_pro15
GROUP BY mapname ASC

It will show the MIN(time) for every mapname but there is no guarantee that it will show the relevant name with the minimum time.

Use this instead (and notice the subquery):

SELECT k.name
     , COUNT(*) AS cnt
FROM kz_pro15 AS k
  JOIN
    ( SELECT mapname 
           , MIN(time) AS time
      FROM kz_pro15
      GROUP BY mapname
    ) AS g
    ON (g.mapname, g.time) = (k.mapname, k.time)
GROUP BY k.name

SELECT名称,min(time)AS时间,count(*)AS记录FROM kz_pro15 GROUP BY name ASC

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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