[英]Get MAX() for each row COUNT() MYSQL
我接下來有兩個表:
表格查詢和表格時間:
id | text id | mid | country
1 hello 1 1 UK
2 hi 2 1 PL
3 sd 3 2 USA
id = mid,國家不同(英國,美國等)。
我需要制作下一個清單:
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.
現在我有了下一個想法:獲取每個國家的哪個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
但是使用這個代碼我收到所有文本的計數。 如
UK text1 30,
UK text2 25,
PL text2 10,
PL text3 5 ..
但我每個國家只需要一個最大值,任何人都可以幫助如何將查詢減少到每個國家的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
╔═════════╦══════╦═════╗
║ COUNTRY ║ TEXT ║ CNT ║
╠═════════╬══════╬═════╣
║ UA ║ sdf ║ 10 ║
║ USA ║ qw ║ 2 ║
╚═════════╩══════╩═════╝
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.