SQLite选择最常见

时间:2015-10-27 13:49:38

标签: sql sqlite

表格如下:

A        B
----------
John     a
John     a
Peter    a
Mary     b
Ann      b
Ann      b

我希望结果是按B分组并从A:

中选择最常用的单词
A        B
----------
John     a
Ann      b

1 个答案:

答案 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(*);