拥有这3张桌子
第一个,EMPLOYEE
//Employee
E# ENAME D#
-----------------------
1 ALI 1
2 SITI 2
3 JOHN 2
4 MARY 3
5 CHIRS 3
第二,PROJECT
//PROJECT
P# PNAME D#
-----------------------
1 Computing 1
2 Coding 3
3 Researching 3
第三,WORKSON
//WORKSON
E# P# Hours
--------------------
1 1 3
1 2 5
4 3 6
所以我的输出应该是
E# ENAME D# TOTAL HOURS/W
--------------------------------------------
1 ALI 1 8
2 SITI 2 0
3 JOHN 2 0
4 MAY 3 6
5 CHIRS 3 0
显示0,因为员工没有可以处理的项目。
我目前使用
的陈述SELECT E.E#,E.NAME,E.D#,NVL(sum(Hours),0) AS "TOTAL HOURS/W"
FROM Employee E,WORKSON W WHERE E.E#=W.E# OR
GROUP BY E.E#,E.NAME,E.D#;
不知道如何选择然后将显示所有员工,而不仅仅是特定的E#。 输出显示为员工没有任何项目工作,应显示0值
答案 0 :(得分:1)
这可以通过
加入员工和WORKSON来完成select
e.`E#`,
e.ENAME,
e.`D#`,
coalesce(tot,0) as `TOTAL HOURS/W`
from Employee e
left join
(
select `E#`,
sum(Hours) as tot
from WORKSON
group by `E#`
)w
on w.`E#` = e.`E#`
group by e.`E#`
<强> DEMO 强>
答案 1 :(得分:0)
您应该使用left outer join
。以下内容适用于MySQL和Oracle:
SELECT E.E#, E.NAME, E.D#,
COALESCE(SUM(Hours), 0) AS "TOTAL HOURS/W"
FROM Employee E LEFT OUTER JOIN
WORKSON W
ON E.E# = W.E#
GROUP BY E.E#, E.NAME, E.D#;