选择带有连接的查询显示计数结果取决于第三个连接表值

时间:2013-01-21 10:27:24

标签: sql-server sql-server-2008 tsql count

在这里 SQL FIDDLE以及带有值的表格架构 我想选择id_emp,fname_emp,TotalProject条件为skillsid的条件(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

3 个答案:

答案 0 :(得分: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 |

答案 1 :(得分: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

答案 2 :(得分: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

首先将employee表作为基础,然后使用技能作为join子句的过滤器,从而减少数据大小。
第二,加入项目表,这样我们就可以算不上了。员工出现在桌子上的次数。

简短又甜蜜。