C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
SQL Aggregate Functions
Types of SQL Aggregation Function1. COUNT FUNCTION
Syntax COUNT(*) or COUNT( [ALL|DISTINCT] expression ) Sample table: PRODUCT_MAST
Example: COUNT() SELECT COUNT(*) FROM PRODUCT_MAST; Output: 10 Example: COUNT with WHERE SELECT COUNT(*) FROM PRODUCT_MAST; WHERE RATE>=20; Output: 7 Example: COUNT() with DISTINCT SELECT COUNT(DISTINCT COMPANY) FROM PRODUCT_MAST; Output: 3 Example: COUNT() with GROUP BY SELECT COMPANY, COUNT(*) FROM PRODUCT_MAST GROUP BY COMPANY; Output: Com1 5 Com2 3 Com3 2 Example: COUNT() with HAVING SELECT COMPANY, COUNT(*) FROM PRODUCT_MAST GROUP BY COMPANY HAVING COUNT(*)>2; Output: Com1 5 Com2 3 2. SUM FunctionSum function is used to calculate the sum of all selected columns. It works on numeric fields only. Syntax SUM() or SUM( [ALL|DISTINCT] expression ) Example: SUM() SELECT SUM(COST) FROM PRODUCT_MAST; Output: 670 Example: SUM() with WHERE SELECT SUM(COST) FROM PRODUCT_MAST WHERE QTY>3; Output: 320 Example: SUM() with GROUP BY SELECT SUM(COST) FROM PRODUCT_MAST WHERE QTY>3 GROUP BY COMPANY; Output: Com1 150 Com2 170 Example: SUM() with HAVING SELECT COMPANY, SUM(COST) FROM PRODUCT_MAST GROUP BY COMPANY HAVING SUM(COST)>=170; Output: Com1 335 Com3 170 3. AVG functionThe AVG function is used to calculate the average value of the numeric type. AVG function returns the average of all non-Null values. Syntax AVG() or AVG( [ALL|DISTINCT] expression ) Example: SELECT AVG(COST) FROM PRODUCT_MAST; Output: 67.00 4. MAX FunctionMAX function is used to find the maximum value of a certain column. This function determines the largest value of all selected values of a column. Syntax MAX() or MAX( [ALL|DISTINCT] expression ) Example: SELECT MAX(RATE) FROM PRODUCT_MAST; 30 5. MIN FunctionMIN function is used to find the minimum value of a certain column. This function determines the smallest value of all selected values of a column. Syntax MIN() or MIN( [ALL|DISTINCT] expression ) Example: SELECT MIN(RATE) FROM PRODUCT_MAST; Output: 10
Next TopicDBMS SQL Join
|