我正在尝试计算每个ID在特定表中出现的次数,如下所示。
Members
ID | NAME
1 | Bob
2 | John
3 | Sally
4 | Hannah
Department
ID | DEPT
1 | Math
1 | English
3 | Math
4 | Math
4 | English
4 | Science
我想按如下方式显示一个表格:
ID | Name | Count(Dept)
1 | Bob | 2
2 | John | 0
3 | Sally | 1
4 | Hannah | 3
我最近一次尝试了几次:
select owner
from table
where (select count(distinct letter) from table group by owner) in
(select max(count(distinct letter)) from table group by owner);
我似乎无法如何正确显示0结果。老实说,当你不想基本上进行自然联接时,我对如何使用感到困惑。
编辑:我已编辑问题以正确显示我想要问的内容。抱歉有任何困惑。
答案 0 :(得分:2)
连接表时,引用每列的WHICH TABLE非常重要。为了帮助缩写整个SQL a"表别名"可以定义和使用而不是完整的表名。
select m.id, m.name, count(d.id) as count_d
from members m
left outer join department d on m.id = d.id
group by m.id, m.name
;
在上面我使用了LEFT OUTER JOIN。一旦定义了外连接,可能会有一些行没有来自department
的行与membesr
中的行匹配,因此您将在与department
相关的所有列中获得NULL行。
对于遇到的每个NON-NULL值,COUNT()函数递增 1,因此括号内包含的内容非常重要。无论如何,COUNT(*)将为每一行增加。 COUNT(d.id)可能会给出零,因为该列中的某些行可能为NULL。
查看 SQL Fiddle
<强> Results 强>:
| ID | NAME | COUNT_D |
|----|--------|---------|
| 1 | Bob | 2 |
| 2 | John | 0 |
| 3 | Sally | 1 |
| 4 | Hannah | 3 |