【问题标题】:Count similar values from table by combining two tables通过组合两个表来计算表中的相似值
【发布时间】:2026-02-16 18:50:01
【问题描述】:

我有两张桌子

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

另一张桌子 表B

id idname
1   stuart
2   bob
3   alex

预期输出

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

我正在使用oracle 9i,是否可以获得预期的结果? 我试过使用 distinct 关键字,但它没有帮助,因为它只提供总数

【问题讨论】:

  • 你在数什么?
  • 加入表格。做一个 GROUP BY。
  • select b.id, b.idname, count(a.id) from tableB b left join tableA a group by b.id, b.idname
  • @jarlh Iam 试图获取计数为 1 、 2 、 3 的出现次数

标签: sql oracle count oracle9i


【解决方案1】:

这很简单。 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;

如果你需要表b中的所有记录,即使表a中没有对应的行,你可以使用外连接:

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;

【讨论】:

  • 我会使用 RIGHT JOIN 并更改 count 以包含零计数
  • RIGHT JOIN... 切换表顺序并改为执行 LEFT JOIN。 (太多人觉得右连接太混乱了。得到“主表左连接可选数据”而不是“可选数据右连接主​​表”要容易得多。)
  • 非常感谢上帝保佑你:)
  • 同意@jarlh,右连接只是向后写的左连接。为什么不from table_b b left join table_a a on a.id = b.id
  • @WilliamRobertson - 那里。已更新。:)
【解决方案2】:

使用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;;

【讨论】:

  • 我会使用 LEFT JOIN 并包括零计数
  • 为什么不在 ORDER BY 中使用列别名? IE。 order by count desc, t1.id.
  • 非常感谢您的帮助...上帝保佑你:)