比较两个表值

时间:2014-10-28 00:56:23

标签: sql sql-server sql-server-2012 nested-queries

另一个SQL问题!

我有几张桌子:

员工有以下字段:

first name, last name, gender, ssn

Works_On包含以下字段:

essn, pno

在Works_On中,essn是PK以及pnopno是指分配给员工的特定项目编号,essn是该员工的社会安全编号。

我的任务是找出哪些员工在项目上工作,其中从事该项目的女性人数超过了男性人数。

到目前为止,我已尝试使用临时表进行此操作,但尚未收到任何输出。

select e.lname, e.ssn, w.pno
from employee e left outer join works_on w
on e.ssn = w.essn, (select count(e1.ssn)
                from employee e1 left outer join works_on w1
                on e1.ssn = w1.essn
                where e1.sex = 'M') as Male(males), 

                (select count(e2.ssn)
                from employee e2 left outer join works_on w2
                on e2.ssn = w2.essn
                where e2.sex = 'F') as Females(females)
where females > males

我不确定我是否正在进行比较,我认为我的临时表正在找错值。

1 个答案:

答案 0 :(得分:1)

首先找出每个项目的性别细分:

select w.pno, sum(case when e.sex = 'M' then 1 else 0 end) as Males,
       sum(case when e.sex = 'F' then 1 else 0 end) as Females
from employee e join
     works_on w
     on e.ssn = w.ess
group by w.pno;

然后加入员工信息并输入条件:

select e.lname, e.ssn, w.pno
from employee e join
     works_on w
     on e.ssn = w.ess join
     (select w.pno, sum(case when e.sex = 'M' then 1 else 0 end) as Males,
             sum(case when e.sex = 'F' then 1 else 0 end) as Females
      from employee e join
           works_on w
           on e.ssn = w.ess
      group by w.pno
     ) g
     on w.pno = g.pno
where females > males;

那就是说,最简单的方法是使用窗口函数:

select e.lname, e.ssn, w.pno
from (select w.pno,
             sum(case when e.sex = 'M' then 1 else 0 end) over (partition by w.pno) as Males,
             sum(case when e.sex = 'F' then 1 else 0 end) over (partition by w.pno) as Females
      from employee e join
           works_on w
           on e.ssn = w.ess
     ) g
where females > males;