如何在netbeans中使用sum case查询

时间:2013-12-22 14:24:10

标签: java sql jdbc

我使用以下查询:

    String qry1 = "SELECT SUM(*) FROM class_cse where Student_ID='" + StudentUserBean.getUserId() + "'";
    try {
        ResultSet rs, rs1;
        rs = db2.stmt.executeQuery(qry1);
        while (rs.next()) {
            String count = rs.getString("SUM(*)");
            jTextField6.setText(count);
        }
    } catch (SQLException ex) {
        Logger.getLogger(AdminInfo.class.getName()).log(Level.SEVERE, null, ex);
    }

现在我使用此查询

    String qry1=select sum(case when maths = 'ABSENT' then 1 else 0 end) + 
            sum(case when ca = 'ABSENT' then 1 else 0 end) + 
            sum(case when cn = 'ABSENT' then 1 else 0 end) 
     from attendance_table;

此查询的总和在jTextField5中设置。你能告诉我如何使用这个查询吗?

1 个答案:

答案 0 :(得分:0)

您有两种选择。第一个是按位置获取结果,而不是按列名称获取结果:

String sum = rs.getString(1);

或:

int sum = rs.getInt(1);

第二个是为结果添加别名,例如myresult:

String qry1=select sum(case when maths = 'ABSENT' then 1 else 0 end) + 
            sum(case when ca = 'ABSENT' then 1 else 0 end) + 
            sum(case when cn = 'ABSENT' then 1 else 0 end) myresult 
     from attendance_table;

并使用它:

String count = rs.getString("myresult");