2016-12-23 111 views
0

我需要從結果集中獲取最小計數,最大計數和總結果集計數。執行查詢後,它會產生多行,我需要從中提取數據。 例如查詢:如何從結果集中獲取最小計數,最大計數和總結果集計數

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.我怎麼能這樣..任何幫助將不勝感激。

+0

'和時間戳' 將永遠是正確的。見http://meta.stackoverflow.com/questions/333952/why-should-i-provide-an-mcve-for-what-seems-to-me-to-be-a-very-simple-sql-query – Strawberry

+0

@Strawberry也許他正在檢查時間戳不爲空。 – JonahCui

回答

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 

然後用

+2

錯誤顯示:每個派生表必須有自己的別名 –

+2

哇!它像魅力一樣工作..最簡單的方法,而不是從Java ..非常感謝 –

+1

最受歡迎@KarthikCP –

1

的Java方法: -

1)將countTotal在一個ArrayList
2)使用Collections類最大值和最小值的方法來找到最大值和最小值。 例如: -

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方法: -

使用最大值,最小值和總數的查詢工會。

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); 
    } 
}