sql plus中的嵌套查询

时间:2014-04-19 17:21:29

标签: php sql sql-server database

create table Employee(e_id number(6) primary key , e_name varchar2(3),e_dept varchar2(30),e_bsal number(10));

create table Allowance(a_id number(6) primary key , a_name varchar2(30),a_val  number(10));

create table Deduct(d_id number(6) primary key , d_name varchar2(30) , d_val number(10));

create table Deduct_trans(e_id number(6), d_id number(6),
constraint e_id_pk foreign key(e_id) references Employee(e_id),
constraint d_id_pk foreign key(d_id) references Deduct(d_id));

create table Allowance_trans(e_id number(6),a_id number(6),
constraint e_id_2_pk foreign key(e_id) references Employee(e_id),
constraint a_id_pk foreign key(a_id) references Allowance(a_id));

create table Salary(e_id number(6),sal number(30),
constraint e_id_3_pk foreign key(e_id) references Employee(e_id));

insert into Employee values(1,'a','Fin',200);
insert into Employee values(2,'b','Pers',220);
insert into Employee values(3,'c','stu',250);

insert into Allowance values(1,'Transpo',100);
insert into Allowance values(2,'Univ',400);
insert into Allowance values(3,'Family',50);
insert into Allowance values(4,'other',250);

insert into Deduct values(1,'Insur',30);
insert into Deduct values(2,'Tax',50);
insert into Deduct values(3,'Secu',60);
insert into Deduct values(4,'socila',10);

insert into Allowance_trans values(1,1);
insert into Allowance_trans values(1,2);
insert into Allowance_trans values(1,3);
insert into Allowance_trans values(2,1);
insert into Allowance_trans values(2,2);
insert into Allowance_trans values(2,3);

insert into Deduct_trans values(1,1);
insert into Deduct_trans values(1,2);
insert into Deduct_trans values(1,3);
insert into Deduct_trans values(2,1);
insert into Deduct_trans values(2,2);
insert into Deduct_trans values(2,3);
insert into Deduct_trans values(2,4);

我需要创建一个名为salary的新表,其中包含两列,第一列是e_id,第二列是工资!!

但首先我要根据这个等式计算每个员工的工资!!

Sal = e_bsal + sum(a_val) - sum(d_val)

1 个答案:

答案 0 :(得分:0)

SELECT E.e_id,( E.e_bsal +total_aval - total_dval ) as Salary
FROM Employee E
INNER JOIN    
( 
  SELECT e_id,SUM(a_val) as total_aval
  FROM Allowance A
  INNER JOIN Allowance_trans AT
    ON AT.a_id=A.a_id
  GROUP BY AT.e_id
) t1

ON t1.e_id=E.e_id

INNER JOIN

( 
  SELECT e_id,SUM(d_val) as total_dval
  FROM Deduct D
  INNER JOIN Deduct_trans DT
  ON D.d_id=DT.d_id
  GROUP BY DT.e_id
) t2

ON t2.e_id=E.e_id