SQL Plus查询 - 多表查询

时间:2013-08-07 14:06:16

标签: sql multiple-tables

这给我带来了更多麻烦。

我有以下示例表:

____________________       ____________      
|   Name|   Number |       | Number   |
|_______|__________|       |__________|
| Alice |     1    |       |    1     |
| Bob   |     2    |       |    1     |
|_______|__________|       |__________|

我希望我的结果是:

_____________________________________
| Name   |   Number  | Count(Number) |
|________|___________|_______________|
| Alice  |     1     |      2        |
| Bob    |     2     |      0        |
|________|___________|_______________|

我要往前走,但我相信这不应该那么棘手。我想我错过了什么。

我修改了戈登的答案:

 select name, number count(t2.number)
 from table1 t1, 
 table2 t2 
 where t1.number = t2.number (+)
 group by t1.number;

1 个答案:

答案 0 :(得分:1)

您需要加入和聚合。但是,连接需要left outer join才能保留所有行:

select name, number, count(t2.number)
from table1 t1 left outer join
     table2 t2
     on t1.number = t2.number
group by t1.name, t1.number;

并且,count()计算第二个表中的非NULL值,因此当没有匹配时,您可以获得0