通过组合两个 table 来计算 table 中的相似值

Count similar values from table by combining two tables

我有两个table

table A
name id 
ABC  1
PQR  2
XYZ  1
QWE  2
DFG  3

另一个table table乙

id idname
1   stuart
2   bob
3   alex

预期输出

id idname count
1  stuart 2
2  bob     2
3  alex   1

我用的是oracle 9i,能不能达到预期的效果? 我试过使用 distinct 关键字但它没有帮助,因为它只提供总计数

很简单。 Joincount:

select b.id, 
    b.idname,
    count(*) as cnt
from table_a a
join table_b b on a.id = b.id
group by b.id, b.idname;

如果你需要tableb中的所有记录,即使在tablea中没有相应的行,你可以使用外连接:

select b.id, 
    b.idname,
    count(a.id) as cnt
from table_a a
right join table_b b on a.id = b.id
group by b.id, b.idname;

同样可以通过使用左连接来实现:

select b.id, 
    b.idname,
    count(a.id) as cnt
from table_b b
left join table_a a on a.id = b.id
group by b.id, b.idname;

使用JOIN从两个表中获取数据并使用聚合函数COUNTGROUP BY

查询

select t1.id, t1.idname, count(t2.name) as count
from TableB t1
left join TableA t2
on t1.id = t2.id
group by t1.id, t1.idname
order by count(t2.name) desc, t1.id;;