简体   繁体   English

获取每行COUNT()MYSQL的MAX()

[英]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). id = mid,国家不同(英国,美国等)。

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. 现在我有了下一个想法:获取每个国家的哪个MID有最大行,并通过mid = id获取文本并对其进行排序。

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? 但我每个国家只需要一个最大值,任何人都可以帮助如何将查询减少到每个国家的1个最大文本?

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 OUTPUT

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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