我有四张桌子:

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

我可以从一个部门的员工那里返回总和(工资),但是我不知道如何计算两个部门的总和,以及如何正确分配两个过程输入。
到目前为止,这是我的程序:
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;

我不确定我是否正确地接近它。
更新
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;
    }

非常感谢您的帮助

最佳答案

您可以使用PreparedStatement执行以下查询:

select sum(salary) from salaries
where emp_id in (select emp_id from dep_emp where dep_id in (?,?));

就像这样:
PreparedStatement ps = connection.prepareStatement(above_sql_as_string);

// To get total salary of 10 and 20 department_id:
ps.setInt(1, 10);
ps.setInt(2, 20);

ResultSet rs = ps.executeQuery();

09-30 17:04
查看更多