使用JDBC进行聚合功能

时间:2014-07-31 17:25:53

标签: jdbc

我想找到大约72列的min,max和avg,类似于代码片段中给出的Adaptation_Luminance。我应该如何遍历所有列并返回它们的平均值,最小值和最大值?我必须使用while循环。但我不确切地知道应该如何实现它。

stmt = conn.createStatement();

        String sql = "select avg(Adaptation_Luminance), min(Adaptation_Luminance) from ras;";

        ResultSet rs =  stmt.executeQuery(sql);
        if(rs.next())
            System.out.println("Average of Adaptation Luminance  is " + rs.getFloat(2));

1 个答案:

答案 0 :(得分:0)

在查询中使用Union将所有72个列值视为72个不同的值。

select 'APAPTATION LUMINANCE' myField,avg(Adaptation_Luminance), min(Adaptation_Luminance) from ras
UNION
select 'TYPE1' myField,avg(TYPE1), min(TYPE1) from ras
UNION
select 'TYPE2' myField,avg(TYPE2), min(TYPE2) from ras
.....
UNION
select 'TYPE72' myField,avg(TYPE72), min(TYPE72) from ras

在java jdbc中使用

String sql = " SELECT 'ADAPTATION LUMINANCE' ........... , min (TYPE72) FROM RAS ";
// Note: Do not include semicolon at end of query string. In JDBC, it will cause error.

boolean isMoreRecordsAvailable = false;
ResultSet rs =  stmt.executeQuery(sql);
        isMoreRecordsAvailable = rs.next();

while (isMoreRecordsAvailable )
{
      System.out.println("Average of "+rs.getString(1)+"  is " + rs.getFloat(2) + " and its Minimum value is : "+rs.getFloat(3));

      isMoreRecordsAvailable = rs.next();
}

您将获得如下输出:

Average of APAPTATION LUMINANCE is 19.11 and its Minimum value is : 9.9
Average of TYPE1 is 11.11 and its Minimum value is 11
Average of TYPE2 is 22.22 and its Minimum value is 2
....
....
Average of TYPE72 is 72.72 and its Minimum value is 7.2