1

这里是带有值的 SQL FIDDLE 和下表模式。
我想选择id_emp,fname_emp,TotalProject一个条件,其skillsidin (1,2)。我试过的查询给出了错误的输出

create table employee_emp(
id_emp int identity(1,1),fname_emp varchar(20),lname_emp varchar(20))
 insert into employee_emp values('John','Cena');
 insert into employee_emp values('Michel','shawn');
 insert into employee_emp values('Jay','mac');
 insert into employee_emp values('David','jackson');

create table skills_skl(
idemp_skl int,idskill_skl int
)
insert into skills_skl values(1,1);
insert into skills_skl values(1,2);
insert into skills_skl values(1,3);
insert into skills_skl values(1,4);
insert into skills_skl values(2,2);
insert into skills_skl values(2,3);
insert into skills_skl values(3,1);
insert into skills_skl values(3,4);
insert into skills_skl values(4,2);

create table employee_ejp(
id_ejp int identity(1,1),idemp_ejp int ,idproject_ejp int)
insert into employee_ejp values(1,1);
insert into employee_ejp values(1,2);
insert into employee_ejp values(1,3);
insert into employee_ejp values(2,3);
insert into employee_ejp values(2,2);
insert into employee_ejp values(3,1);
insert into employee_ejp values(4,4);

我试过的查询

1)

select a.id_emp,a.fname_emp,count(b.id_ejp) TotalP from employee_emp a
join employee_ejp b on a.id_emp=b.idemp_ejp 
group by a.id_emp,a.fname_emp

2)

select a.id_emp,a.fname_emp,count(b.id_ejp) TotalP from employee_emp a
join employee_ejp b on a.id_emp=b.idemp_ejp join skills_skl c on c.idskill_skl=a.id_emp
where c.idskill_skl in (1,2)
group by a.id_emp,a.fname_emp
4

3 回答 3

1

这是简单的方法:

;with emps_1_2 as (
select distinct a.id_emp
  from employee_emp a
  join skills_skl c on c.idemp_skl=a.id_emp     --Be carefull here!
  where c.idskill_skl in (1,2)
)  
select emp.id_emp,
       emp.fname_emp,
       coalesce( COUNT(ejp.id_ejp), 0) as TotalProject 
from       employee_emp emp 
inner join emps_1_2 emp12 
        on emp.id_emp = emp12.id_emp
 left join employee_ejp ejp 
        on emp.id_emp=ejp.idemp_ejp
group by emp.id_emp,emp.fname_emp

结果:

| ID_EMP | FNAME_EMP | TOTALPROJECT |
-------------------------------------
|      4 |     David |            1 |
|      3 |       Jay |            1 |
|      1 |      John |            3 |
|      2 |    Michel |            2 |
于 2013-01-21T10:35:49.777 回答
1
select distinct a.id_emp, COUNT(idproject_ejp) over(partition by a.id_emp) 
from #employee_emp a join #skills_skl b 
on a.id_emp = b.idemp_skl
join #employee_ejp c 
on a.id_emp = c.idemp_ejp
where b.idskill_skl in (1,2)
group by a.id_emp,idproject_ejp
于 2013-01-21T10:42:24.510 回答
0

这应该可以解决问题:

select emp.id_emp, emp.fname_emp, count(proj.idemp_ejp) as project_count  
from employee_emp emp  
join skills_skl sk  
on emp.id_emp=sk.idemp_skl and sk.idskill_skl in (1,2)  
join employee_ejp proj  
on proj.id_ejp=emp.id_emp  
group by emp.fname_emp, emp.id_emp

首先以员工表为基础,然后使用技能作为连接子句的过滤器,从而减少数据大小。
其次,加入项目表,以便我们可以计算编号。员工出现在表格中的次数。

短而甜。

于 2013-01-21T10:57:03.240 回答