如何在同一语句中组合两个SUM查询?

时间:2016-12-26 17:39:57

标签: java mysql stored-procedures

我有4张桌子:

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;

我不确定我是否正确接近它。

更新

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;
    }

任何帮助非常感谢

1 个答案:

答案 0 :(得分:3)

您可以使用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();