我有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,那麼我想爲什麼需要使用查詢進行更難的計算。我對嗎?? –