java编程和sql除以两列的总和

时间:2016-03-13 10:10:48

标签: java mysql sql

      try{
       String sum="",sum1="";
          String sql = "select sum(unit) from Result where idNumber=?";
          pst=conn.prepareStatement(sql);
          pst.setString(1,issearchTextField.getText());
          rs=pst.executeQuery();
          if(rs.next()){
           sum = rs.getString("sum(unit)");

          }



          String sql1 = "select sum(ugp) from Result where idNumber=?";
          PreparedStatement pst1=conn.prepareStatement(sql1);
          pst1.setString(1,issearchTextField.getText());
           ResultSet rs1=pst.executeQuery();
          if(rs1.next()){
           sum1 = rs1.getString("sum(ugp)");

          }

          String rst = (sum)/(sum1);
         ccnameTextField.setText(rst);
      }
      catch(Exception ex){

      }
       finally{
    try{
        rs.close();
        pst.close();
    }
    catch(Exception e){
    }
    }

/ *大家好,请我试着得到两列的总和        在数据库中,并将这些将作为输出的总和除以textField,下面就是我试过的。请帮帮我... * /

2 个答案:

答案 0 :(得分:3)

您可以在单个查询中执行此操作

select sum(unit)/NULLIF(sum(ugp),0)
from Result 
where idNumber=?

NULLIF用于避免除以零错误

答案 1 :(得分:0)

对于2位十进制格式,您可以这样使用:

double d = 1.234567;
DecimalFormat df = new DecimalFormat("#.##");
System.out.print(df.format(d)); //1.23