很抱歉Oracle-Noob的问题,但我遇到的问题是我正在尝试运行,而且似乎无法弄清楚如何编写它。
如果我将查询分成两部分,我会得到每个部分的正确信息。参见:
select NVL (skill.category, 'Total:') "Skill Category",
count (training.code) "# of Trainings"
from skill join training on skill.code = training.code
group by rollup (skill.category);
返回:
Skill Category # of Trainings
--------------- --------------
Database 2
HR 1
Leadership 1
Printing 1
Sales 3
Web Design 5
Total: 13
同样,我得到以下第二个查询:
select NVL (skill.category, 'Total:') "Skill Category",
count (project.code) "projects req training"
from skill join project on skill.code = project.code
group by rollup (skill.category);
Skill Category projects req training
--------------- ---------------------
Database 2
Printing 3
Web Design 5
Total: 10
然而,当我尝试组合这些查询时,我的结果搞砸了:
select NVL (skill.category, 'Total:') "Skill Category",
count (training.code) "# of Trainings",
count (project.code) "Projects Requiring Skill"
from skill join training on skill.code = training.code
left join project on training.code = project.code
group by rollup (skill.category);
Skill Category # of Trainings Projects Requiring Skill
--------------- -------------- ------------------------
Database 4 4
HR 1 0
Leadership 1 0
Printing 3 3
Sales 3 0
Web Design 13 13
Total: 25 20
我在这里做错了什么?我非常感谢任何帮助,对不起,如果我遗漏了一些明显的东西!
答案 0 :(得分:0)
问题在于您加入了数据倍增。您有两个1-n关系,介于技能和培训之间以及培训和项目之间。结果是组合的倍增。
解决方案是分别进行两个摘要,然后使用join:
进行组合select st.*, "projects req training"
from (select NVL(skill.category, 'Total:') "Skill Category",
count(training.code) "# of Trainings"
from skill left outer join
training
on skill.code = training.code
group by rollup (skill.category)
) st join
(select NVL(skill.category, 'Total:') "Skill Category",
count(project.code) "projects req training"
from skill left outer join
project
on skill.code = project.code
group by rollup (skill.category)
) sp
on st."Skill Category" = sp."Skill Category"
在这个版本中,我在子查询中使用left outer join
,以确保每个子查询返回所有技能。这允许我在下一级使用inner join
。我已将rollup
留在子查询中,而不是在外部进行额外的聚合。