2014-04-14 93 views
0

我希望每個員工部門獲得最多的明星,所以從表csereduxresponses中添加來自每個部門的明星,然後使用employee.cse_dept(每個部門的#of員工)進行劃分。 employedept = dept_id,employee = emp_id。 我做了一個模擬表來簡化。簡化連接查詢?

create table csereduxresponds (employeedept int, employee int, stars int); 

insert into csereduxresponds values(1,1,1); 
insert into csereduxresponds values(1,1,0); 
insert into csereduxresponds values(1,1,1); 
insert into csereduxresponds values(1,2,1); 
insert into csereduxresponds values(1,2,0); 
insert into csereduxresponds values(3,3,1); 
insert into csereduxresponds values(3,3,1); 
insert into csereduxresponds values(4,3,1); 
insert into csereduxresponds values(4,3,0); 
insert into csereduxresponds values(4,3,1); 
insert into csereduxresponds values(4,3,1); 
insert into csereduxresponds values(5,4,0); 
insert into csereduxresponds values(5,4,1); 
insert into csereduxresponds values(5,4,1); 

create table employee (dept_id int,emp_id int,cse_dept int); 

insert into employee values (1,1,14); 
insert into employee values (1,2,14); 
insert into employee values (3,3,8); 
insert into employee values (5,4,9); 
insert into employee values (6,5,10); 

create table csereduxdepts(csedept_id int, dept_name varchar(25)); 
insert into csereduxdepts(1,'dapartmen one'); 
insert into csereduxdepts(2,'dapartmen two'); 
insert into csereduxdepts(3,'dapartmen 3'); 
insert into csereduxdepts(4,'dapartmen 4'); 
insert into csereduxdepts(5,'dapartmen 5'); 
insert into csereduxdepts(6,'dapartmen 6'); 

我有這個疑問,做類似的東西,它得到每個員工的total_stars,而不是由部門:

select a.employee, a.execoffice_status,a.employeedept, b.csedept_id as department_id , b.csedept_name as department_name, 
    SUM(execoffice_status) as total_stars,RANK() OVER(ORDER BY SUM(execoffice_status)desc)as rnk 
    from intranet.dbo.CSEReduxResponses a join intranet.dbo.CSEReduxDepts b 
    on b.csedept_id = a.employeedept 
    group by employee,execoffice_status,employeedept,csedept_id,csedept_name 
    order by rnk 

我放棄加入其中有部門名稱的另一個表。 在這裏,我想輸出部門名稱和星級/ cse_dept

+0

你能顯示你所需的輸出? –

回答

0

根據您提供的內容,以下是每個部門每名員工的星級總和除以員工每個部門的靜態值(cse_dept)。 PerCSE以百分比顯示。

SELECT employeedept 
     , employee 
     , SUM(stars) NumStars 
     , MAX(cse_dept) EmployeeDeptCount 
     , SUM(stars) * 100.00/MAX(cse_dept) AS PerCSE 
FROM employee e 
JOIN csereduxresponds c 
     ON employeedept = dept_id 
      AND employee = emp_id 
GROUP BY employeedept 
     , employee 

下面是按照提供的條件連接。

SELECT * 
FROM employee e 
JOIN csereduxresponds c 
     ON employeedept = dept_id 
      AND employee = emp_id 
0
;WITH CTE 
AS 
( 

select employeedept 
, employe From employee e 
) 
Select c.employeedept 
, c.employe 
, SUM(cc.stars) NumStars 
, MAX(cc.cse_dept) EmployeeDeptCount 
, SUM(cc.stars) * 100.00/MAX(cc.cse_dept) AS PerCSE 
From CTE C 
INNER JOIN csereduxresponds cc 
ON C.employeedept = cc.dept_id 
AND C.employee = CC.emp_id