如何从结果集中获取最小计数,最大计数和总结果集计数

时间:2016-12-23 08:12:19

标签: java mysql jdbc

我需要从结果集中获得最小计数,最大计数和总结果集计数。执行查询后,它会生成多行,我需要从中提取数据。 例如查询:

SELECT count(*) AS `countTotal`,`admission_no`,`course`  FROM  `attendance` WHERE  `course` = '15' AND `timestamp` AND  `admission_no` !='0' AND `timestamp` BETWEEN '2016-04-01 00:00:00.0' AND '2017-03-31 00:00:00.0' GROUP BY `admission_no` ORDER BY `countTotal`  DESC

OUT PUT

countTotal  admission_no    course
4            2304             15
4            2442             15
3            2777             15
2            2967             15
2            3288             15

我试过了:

if (overallTotalClassRow.next()) {
    maxclassaverage = overallTotalClassRow.getInt(1);
}

但是这会给出最大的价值。即4。

我需要得到4和2作为最大值和最小值,总计数为5.我怎么能这样做..任何帮助都会受到赞赏。

3 个答案:

答案 0 :(得分:2)

试试这个。

        select min(countTotal) as MinCount ,max(countTotal) as MaxCount, 
        count(*) as totalCount  from
        (SELECT count(*) AS `countTotal`,`admission_no`,`course` 
         FROM  `attendance` WHERE  `course` = '15' AND `timestamp` 
         AND  `admission_no` !='0' AND `timestamp` 
         BETWEEN '2016-04-01 00:00:00.0' AND '2017-03-31 00:00:00.0' 
         GROUP BY `admission_no` 
         )a

然后使用

答案 1 :(得分:1)

  

Java方法: -

1)将countTotal放入ArrayList中 2)使用Collections类max和min方法查找最大值和最小值。 例如: -

Comparator<String> comparator = new Comparator<String>() {
        @Override
        public int compare(String o1, String o2) {
            return Integer.valueOf(o1).compareTo(Integer.valueOf(o2));
        }
    };
int max=Collections.max(list, comparator);

3)ArrayList.size()查找总计数。

  

SQL方法: -

在联合中使用最大,最小和总计数查询。

答案 2 :(得分:1)

我认为最简单的方法是:

int maximum = 0;
int minimum =0;
int totalCount =0;

if (overallTotalClassRow.next()) {
    totalCount +=1;
    if(totalCount ==1) {
        maximum = overallTotalClassRow.getInt(1);
        minimum = overallTotalClassRow.getInt(1);
    }
    if (overallTotalClassRow.getInt(1)> maximum) {
        maximum = overallTotalClassRow.getInt(1); 
    }
    if (overallTotalClassRow.getInt(1)< maximum) {
        minimum = overallTotalClassRow.getInt(1); 
    }
}