表格如下:
A B
----------
John a
John a
Peter a
Mary b
Ann b
Ann b
我希望结果是按B分组并从A:
中选择最常用的单词A B
----------
John a
Ann b
答案 0 :(得分:0)
首先我计算B,A组合的数量,然后按BI计算最大数量(MaxN),最后在外部查询中再次计算计数,但只显示具有maxN=COUNT(*)
的行数:
SELECT t.B, t.A, COUNT(*) as N
FROM Table t LEFT JOIN
(SELECT B, MAX(N) AS MaxN
FROM (
SELECT B, A, count(*) as N
FROM Table
GROUP BY B, A) as c
GROUP BY B) as mx on t.B=mx.B
GROUP BY t.B, t.A
HAVING mx.MaxN=COUNT(*);