获取x行数,其中id = id(其他表),其行数最多且为

时间:2015-05-27 12:46:15

标签: mysql sql greatest-n-per-group

x =无关紧要

表A

0 row0
1 row1
2 row2

表B

0 x
1 x
0 X
2 X
2 X
0 x

在这个例子中有3行0,2行2和1行1.

我想得到例如行数最多的两行。

期望的结果:

0 row0 ==> because 3 rows in b is the highest amount.
2 row2 ==> because 2 rows in b is the second highest amount.

到目前为止我的尝试:

SELECT Id, Name FROM A
WHERE Id =
(
SELECT IdB FROM B
GROUP BY IdB 
ORDER BY count(IdB) DESC
LIMIT 2
)

编辑:我使用mysql

感谢

4 个答案:

答案 0 :(得分:0)

不确定如何处理关系。

这样做是基于你的ID加入(learn more about joins)两个表然后聚合计算B.IDB出现次数的结果并显示该计数以及表A中的名称

SELECT A.Name, count(B.IDB) cnt
FROM A
INNER JOIN IDB
 on A.ID = B.IDB
GROUP BY A.Name
ORDER BY count(B.IDB) desc
LIMIT 2

但是你的例子应该返回

Name cnt
row0 3
row2 2

答案 1 :(得分:0)

您希望JOIN id一起SELECT A.id, A.name FROM A join B on A.id = B.id GROUP BY A.name ORDER BY count(B.id) desc LIMIT 2 您的牌桌。{/ p>

MathUtil.CalculateSin(angle)

SQLFIDDLE

这将返回与上述示例匹配的输出。

答案 2 :(得分:0)

- 样本表

- 表格架构

create table A (id int, name varchar(10))

 insert into A 
 values (0, 'row0')
  insert into A 
 values (1, 'row1')
 insert into A 
 values (2, 'row2')

 select * from A

- 表格架构

 create table B (id int, name varchar(10))

 insert into B 
 values (0, 'X')
 insert into B 
 values (0, 'X')
 insert into B 
 values (0, 'X')
 insert into B 
 values (0, 'X')
   insert into B 
 values (1, 'X')
 insert into B 
 values (2, 'X')
 insert into B 
 values (2, 'X')
 insert into B 
 values (2, 'X')
 insert into B 
 values (2, 'X')
 insert into B 
 values (2, 'X')
 insert into B 
 values (2, 'X')

 select * from B

- 查询

 select Top 2 A.name, count(B.id) from A
  inner join B on A.id = b.id
   group by A.name
 order by  count(A.name) desc

答案 3 :(得分:0)

你可以试试;

select a.name, b.count
  from A a,
       (select idB, count(idB) count from B group by idB) b
 where a.id = b.idB
   and count > 1