简体   繁体   中英

Get MAX() for each row COUNT() MYSQL

I have next 2 tables:

table querys and table time:

id | text     id | mid | country
1    hello     1    1       UK
2     hi       2    1       PL
3     sd       3    2       USA

id = mid, countries are different (UK, USA and so on).

I need to make next list:

UK - text 30 rows (this text has most mid in table 2 for UK)
USA - text 25 rows
PL - text 10 rows
...
SS - text 1 rows.

For now i have next idea: Get which MID for each country has max rows and get text by mid=id and sort it.

SELECT time.country,querys.text,COUNT(mid) AS cnt 
     FROM time INNER JOIN `querys` ON(time.mid = querys.id) 
      GROUP BY mid 
      ORDER BY country,cnt
      DESC

But with this code i recieve all text with count of it. Such as

UK text1 30, 
UK text2 25, 
PL text2 10, 
PL text3 5 ..

But i need only one max for each country, could anyone help how to cut the query to 1 max text for each country?

SELECT  a.country, 
        b.text, 
        COUNT(*) AS cnt 
FROM    time a
        INNER JOIN querys b
            ON a.mid = b.id
        INNER JOIN
        (
            SELECT  Country, 
                    MAX(totalCount) max_count
            FROM
                    (
                        SELECT  Country, Mid, 
                        COUNT(*) totalCount
                        FROM    time
                        GROUP   BY Country, Mid
                    ) s
            GROUP   BY Country
        ) c ON a.country = c.country
GROUP   BY a.country, b.text, c.max_count
HAVING  COUNT(*) = c.max_count
ORDER   BY cnt DESC

OUTPUT

╔═════════╦══════╦═════╗
║ COUNTRY ║ TEXT ║ CNT ║
╠═════════╬══════╬═════╣
║ UA      ║ sdf  ║  10 ║
║ USA     ║ qw   ║   2 ║
╚═════════╩══════╩═════╝

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