1. 程式人生 > >oracle having sum group by 詳解

oracle having sum group by 詳解

Aggregate functions (like SUM) often need an added GROUP BY functionality. 

集合函式(類似SUM)經常需要用GROUP BY來進行功能性的補充。 


GROUP BY... 

GROUP BY... was added to SQL because aggregate functions (like SUM) return the aggregate of all column values every time they are called, and without the GROUP BY function it was impossible to find the sum for each individual group of column values. 



GROUP BY...之所以加到SQL中去是因為集合函式(像SUM)每當他們被訪問時就會返回集合所有欄目的值,而且沒有GROUP BY的話就不能夠找出單獨一種欄目所累計的值了。 

The syntax for the GROUP BY function is: 

使用GROUP BY函式的語法為: 

SELECT column,SUM(column) FROM table GROUP BY column 





GROUP BY Example 

舉例 

This "Sales" Table: 

這是張名為"Sales"的表: Company Amount 

W3Schools 5500 
IBM 4500 
W3Schools 7100 


And This SQL: 

這是條SQL: 

SELECT Company, SUM(Amount) FROM Sales 

 





Returns this result: 

返回的結果為: Company SUM(Amount) 
W3Schools 17100 
IBM 17100 
W3Schools 17100 


The above code is invalid because the column returned is not part of an aggregate. A GROUP BY clause will solve this problem: 



上面這些程式碼幾乎是無效的,因為欄目所返回的數值並不屬於我們想要的那種合計。使用 GROUP BY子句可以解決這個問題: 

SELECT Company,SUM(Amount) FROM Sales 

GROUP BY Company 

 





Returns this result: 

返回的結果為: Company SUM(Amount) 
W3Schools 12600 
IBM 4500 




HAVING... 

HAVING... was added to SQL because the WHERE keyword could not be used against aggregate functions (like SUM), and without HAVING... it would be impossible to test for result conditions. 

WHERE關鍵字在使用集合函式時不能使用,所以在集合函式中加上了HAVING來起到測試查詢結果是否符合條件的作用。 

The syntax for the HAVING function is: 

HAVING的使用語法為: 

SELECT column,SUM(column) FROM table 

GROUP BY column 

HAVING SUM(column) condition value

 

 

 



This "Sales" Table: 

這是名為"Sales"的表: Company Amount 
W3Schools 5500 
IBM 4500 
W3Schools 7100 


This SQL: 

SQL語句: 

SELECT Company,SUM(Amount) FROM Sales 

GROUP BY Company 

HAVING SUM(Amount)>10000 

 


Returns this result 

返回的結果為 Company SUM(Amount) 
W3Schools 12600