w3resource

SQL MAX() with COUNT()

MAX() with Count function

In this part, you will see the usage of SQL COUNT() along with the SQL MAX().

Example:

To get the maximum number of agents as column alias 'mycount' from the 'orders' table with the following condition -

1. 'agent_code' should be in a group,

the following SQL statement can be used :

SELECT MAX (mycount) 
FROM (SELECT agent_code,COUNT(agent_code) mycount 
FROM orders 
GROUP BY agent_code);

Sample table: orders


Output:

MAX(MYCOUNT)
------------
           7

Pictorial Presentation :

SQL MAX() function with COUNT example

SQL MAX() and COUNT() with HAVING

To get data of 'agent_code', and number of agents for each group of 'agent_code' from the orders table with the following conditions -

'agent_code' for a group will be equal to the result of an outer query [SELECT MAX(agent_code).......] with following condition -

the outer query produce the maximum number of agents mentioned as 'mycount' from an inner query [SELECT agent_code,
COUNT(agent_code) mycount FROM orders GROUP BY agent_code] with following condition -

the inner query produced the data 'agent_code' number of agents as column alias 'mycount' from the 'orders' table with the following condition -

'agent_code' should be in a group,

the following SQL statement can be used :

SELECT agent_code, COUNT(agent_code) 
FROM orders  GROUP BY agent_code 
HAVING COUNT (agent_code)=( 
SELECT MAX(mycount) 
FROM ( 
SELECT agent_code, COUNT(agent_code) mycount 
FROM orders 
GROUP BY agent_code));

Sample table: orders


Output:

AGENT_CODE COUNT(AGENT_CODE)
---------- -----------------
A002                       7

SQL MAX() function with COUNT WITH HAVING example

Note: Outputs of the said SQL statement shown here is taken by using Oracle Database 10g Express Edition

Here is a slide presentation of all aggregate functions.

Practice SQL Exercises

Want to improve the above article? Contribute your Notes/Comments/Examples through Disqus.

Previous: Max Date
Next: Min function



Follow us on Facebook and Twitter for latest update.

SQL: Tips of the Day

Difference between primary key and unique key:

Primary Key:

  • There can only be one primary key constraint in a table
  • In some DBMS it cannot be NULL - e.g. MySQL adds NOT NULL
  • Primary Key is a unique key identifier of the record

Unique Key:

  • Can be more than one unique key in one table
  • Unique key can have NULL values
  • It can be a candidate key
  • Unique key can be NULL ; multiple rows can have NULL values and therefore may not be considered "unique"

Ref : https://bit.ly/2XNgBd0