我有4个表:如何在同一个语句中合并两个SUM查询?
employees
emp-id | fname | lname
-------------
departments
dep-id | dep-name
-------------
dep-emp
emp-id | dep-id
-------------
salaries
emp-id | salary
我想编写一个程序,可以让用户输入2个数字,从这些部门的所有员工得到的工资相结合。
例
Enter department no: 6
Enter second department no: 3
背景计算
department 6 has 2 employees
employee 1 earns 25,000
employee 2 earns 22,000
Total = 47,000
department 3 has 3 employees
employee 1 earns 40,000
employee 2 earns 45,000
employee 3 earns 35,000
Total = 130,000
Combined Total = 177,000
输出:
Combined salary total for those departments is: 177,000
我可以返回从员工SUM(工资)在一个部门,但我不能弄清楚如何总结两个部门,以及如何分配这两个程序正确输入。
这是我的程序至今:
CREATE PROCEDURE getDepartmentSalaryTotal(IN in_dep1 int(11), IN in_dep2 int(11))
SELECT SUM(salary) FROM salaries
JOIN employees
ON (salaries.emp-id = employees.emp-id)
JOIN dep-emp
ON (employees.emp-id = dep-emp.emp-id)
WHERE dep-emp.dep-id = // in_dep1 + in_dep2;
我不知道我是正确的接近它。
UPDATE
Java代码:
public static int getDepartmentSalaryTotal(Connection conn, int dep1, int dep2) {
int salaryTotal = 0;
try {
java.sql.PreparedStatement pst = conn.prepareStatement("{call getDepartmentSalaryTotal(?)}");
pst.setInt(1, dep1);
pst.setInt(2, dep2);
ResultSet rs = pst.executeQuery();
while (rs.next()){
salaryTotal = rs.getInt(1);
}
rs.close();
pst.close();
}
catch (SQLException e) {
e.printStackTrace();
}
return salaryTotal;
}
任何帮助非常赞赏
难道你不是在java吗? –
@RakibulIslam不可能从sql查询中得到结果吗? – sol
这也是可能的,但如果您使用的是java,那么我想为什么需要使用查询进行更难的计算。我对吗?? –