我需要在MySQL Count Query上返回Last Record,但MySQL总是返回第一条记录
table : author
+--------+----------------------+-----------+----------------+
| aut_id | aut_name | country | home_city |
+--------+----------------------+-----------+----------------+
| AUT001 | William Norton | UK | Cambridge |
| AUT002 | William Maugham | Canada | Toronto |
| AUT003 | William Anthony | UK | Leeds |
| AUT004 | S.B.Swaminathan | India | Bangalore |
| AUT005 | Thomas Morgan | Germany | Arnsberg |
| AUT006 | Thomas Merton | USA | New York |
| AUT007 | Piers Gibson | UK | London |
| AUT008 | Nikolai Dewey | USA | Atlanta |
| AUT009 | Marquis de Ellis | Brazil | Rio De Janerio |
| AUT010 | Joseph Milton | USA | Houston |
| AUT011 | John Betjeman Hunter | Australia | Sydney |
| AUT012 | Evan Hayek | Canada | Vancouver |
| AUT013 | E. Howard | Australia | Adelaide |
| AUT014 | C. J. Wilde | UK | London |
| AUT015 | Butler Andre | USA | Florida |
+--------+----------------------+-----------+----------------+
SELECT country,COUNT(*) as total , aut_name
FROM author
GROUP BY country
ORDER BY total desc;
+-----------+----------+
问题是我总是在每个国家首先记录 比如John Betjeman Hunter对E. Howard&所以..
需要获得结果
+-----------+----------+
| country | COUNT(*) | aut_name
+-----------+----------+
| UK | 4 | C. J. Wilde ------> Last Entry in UK
| USA | 4 | Butler Andre ------> Last Entry in USA
| Australia | 2 | E. Howard
| Canada | 2 | Evan Hayek
| Brazil | 1 | Marquis de Ellis
| Germany | 1 | Thomas Morgan
| India | 1 | S.B.Swaminathan
+-----------+----------+
答案 0 :(得分:4)
SELECT t2.country,
t2.author_count,
t1.aut_name
FROM author t1
INNER JOIN
(
SELECT country, COUNT(*) AS author_count, MAX(aut_id) AS aut_id
FROM author
GROUP BY country
) t2
ON t1.country = t2.country AND
t1.aut_id = t2.aut_id
ORDER BY t2.author_count DESC
在这里演示: