我在Oracle SQL中有两个表:
PROJECT( PID ,Pname,预算, DID )
DIVISION( DID ,Dname)
粗体 =主键
斜体 =外键
我想列出比分部营销有更多项目的部门。
这是我的代码:
select dname as "Division"
from division d, project p
where d.did = p.did
group by dname
having count(pid) >= all
(select count(p.pid)
from project p, division d
where p.did = d.did and d.dname = 'marketing')
我会返回正确的记录,但也会返回营销记录。如何从结果中排除营销记录?
答案 0 :(得分:3)
为什么不通过添加以下内容从初始SQL中排除营销记录:
and d.dname != 'marketing'
到第一个where
子句。
答案 1 :(得分:0)
您可以通过公共表表达式(WITH子句)获得效率,以按部门聚合计数,然后您可以查询...
with cte as (
select dname,
count(*) projects
from project p,
division d
where p.did = d.did
group by dname)
select dname,
projects
from cte
where projects > (select projects
from cte
where dname = 'Marketing)