如何在Java中的结果集中有多个选择语句

时间:2015-07-23 16:50:23

标签: java oracle select resultset

我目前遇到的问题是我想选择一个列并对值求和。然后我想在同一个表中总结另一列。目标是获取这两个总结列并减去它们以获得输出。我对此的用处是休假时间。每个星期,员工都会享受数小时的假期。然后当它们被使用时,它们位于不同的列中。我需要拿出他们可以使用的假期总数。 这就是我所拥有的:

try
    {
         //Getting Information FROM EMPLOYEE_TIME_LOG for Vacation
            Statement vacationLogstmt = dbConn.createStatement();
            ResultSet vacationLogSet = vacationLogstmt.executeQuery(
                         "(SELECT SUM(vacation_gained) FROM employee_time_log WHERE employee_id_number = " +userInputIdNumber + "), " +
                         "(SELECT SUM(vacation_used) FROM employee_time_log WHERE employee_id_number = " +userInputIdNumber + "), " +
                     "GROUP BY vacation_gained, vacation_used");

           vacationLogSet.next();
           String strVacationEarned = vacationLogSet.getString(1);
           String strVacationUsed = vacationLogSet.getString(2);
           Double vacationEarned = Double.parseDouble(strVacationEarned);
           Double vacationUsed = Double.parseDouble(strVacationUsed);
           Double totalVacation = (vacationEarned - vacationUsed); 
           String strTotalVacation =Double.toString(totalVacation);
           txtVacationTotal.setText(strTotalVacation);
    }
    catch (SQLException e)
    {
          //throw new JboException(e);
            System.err.println(e);
            String connectionError = "Problem with the database, please contact MIS.";
            JOptionPane.showMessageDialog(new JFrame(), connectionError, "Database Error",JOptionPane.ERROR_MESSAGE);
            txtUserSignIn.setText("");
            txtUserSignIn.requestFocus();      
    }

我收到错误: java.sql.SQLSyntaxErrorException:ORA-00933:SQL命令未正确结束

这甚至可以在一个结果集中完成吗?或者我需要制作单独的结果集来执行此操作。

1 个答案:

答案 0 :(得分:1)

你的sql有几个问题。首先,您不能用逗号分隔多个选择。相反,您应该有一个具有多个列的选择。其次,您不应该通过vacation_gained,vacation_used进行分组,因为您在聚合函数中使用这些字段。 sql应该如下:

"(SELECT SUM(vacation_gained), SUM(vacation_used) FROM employee_time_log WHERE employee_id_number = " + userInputIdNumber + ")";

或者,如果您只对剩下的休假时间感兴趣,您也可以将数学作为查询的一部分:

"(SELECT SUM(vacation_gained) - SUM(vacation_used) as total_vacation FROM employee_time_log WHERE employee_id_number = " + userInputIdNumber + ")";