Sql запросы как найти максимальное

SQL stands for Structured Query Language and is used to create, maintain and retrieve the data from relational databases. Relational Database Management Systems (RDBMS) like MySQL, MS Access, Oracle, and SQL Server use SQL as their standard database language. Here we are going to see the SQL query for Finding Maximum Values in Rows. Let us understand it by creating a database named “CSEportal”. 

Creating Database :

Syntax : 
CREATE DATABASE <DatabaseName>;
Example :
CREATE DATABASE CSEportal;
Output :
Query returned successfully in 3 secs 817 msec.

Using the Database :

Syntax :
USE <DatabaseName>;
Example :
USE CSEportal;

Using the above commands, we have successfully created our database named “CSEportal”, now we need to create a table(Relation) named “GeeksforGeeks” in this database. 

Creating table :

Syntax :
CREATE TABLE TableName (field1 dataType1 , field2 dataType2...fieldN dataTypeN);
Example : 
CREATE TABLE GeeksforGeeks(
sno int, 
Description VARCHAR(40), 
courses VARCHAR(40));

This will create an empty table, so let us populate our table with some records using the INSERT INTO command to perform the actual operations on the tables. 

Inserting records in the table :

Syntax :
INSERT INTO tablename (field1,field2,...fieldN) VALUES (value1,value2...valueN);
Example :
INSERT INTO GeeksforGeeks(sno,Description,Courses) VALUES(1,'Cse Portal','DBMS');

Similarly, we can fill our table using this INSERT INTO command. To see the created table, we can run the SELECT command which is shown below:

SELECT * from GeeksforGeeks;

Output :

Our Table “GeeksforGeeks”

Now we can move ahead to write our SQL query for finding maximum values in all the rows, This can be done using MAX(field) function in SQL. Let us try to retrieve the maximum value of the field “Description” as shown below:

Select max(Description) as Maximum from GeeksforGeeks;

Here we have used the ‘as ‘ keyword just to change the name of the resulting field as shown in the output below:

Output : 

Here we have got ‘well explained’ as the output since it is the maximum value out of all the rows of the table. Let us try to apply this on the field holding some numeric values to get a more clear idea. 

 Select max(sno) from GeeksforGeeks;

Output : 

Clearly, 4 is the maximum value out of all the rows of the table, hence we have got 4 as our output. Also, here we have not used the ‘as’ keyword, so in the resulting field, we have got ‘max(sno)’ as its name. It is an optional step and can be done in the same manner as shown above. We can also retrieve maximum values of more than one field out of all the rows using a single query as shown below:

Query:
Select max(sno),max(description) from GeeksforGeeks;

Output:
max(sno)    max(description)

4            well explained

So here, we have retrieved the maximum value of two fields (out of all the rows) using a single query only.

Last Updated :
07 Apr, 2021

Like Article

Save Article

This SQL tutorial explains how to use the SQL MAX function with syntax and examples.

Description

The SQL MAX function is used to return the maximum value of an expression in a SELECT statement.

Syntax

The syntax for the MAX function in SQL is:

SELECT MAX(aggregate_expression)
FROM tables
[WHERE conditions];

OR the syntax for the MAX function when grouping the results by one or more columns is:

SELECT expression1, expression2, ... expression_n,
       MAX(aggregate_expression)
FROM tables
[WHERE conditions]
GROUP BY expression1, expression2, ... expression_n;

Parameters or Arguments

expression1, expression2, … expression_n
Expressions that are not encapsulated within the MAX function and must be included in the GROUP BY clause at the end of the SQL statement.
aggregate_expression
This is the column or expression from which the maximum value will be returned.
tables
The tables that you wish to retrieve records from. There must be at least one table listed in the FROM clause.
WHERE conditions
Optional. These are conditions that must be met for the records to be selected.

Example – With Single Expression

The simplest way to use the SQL MAX function would be to return a single field that calculates the MAX value.

For example, you might wish to know the maximum salary of all employees.

SELECT MAX(salary) AS "Highest salary"
FROM employees;

In this SQL MAX function example, we’ve aliased the MAX(salary) field as “Highest salary”. As a result, “Highest salary” will display as the field name when the result set is returned.

Example – Using SQL GROUP BY Clause

In some cases, you will be required to use the SQL GROUP BY clause with the SQL MAX function.

For example, you could also use the SQL MAX function to return the name of each department and the maximum salary in the department.

SELECT department, MAX(salary) AS "Highest salary"
FROM employees
GROUP BY department;

Because you have listed one column in your SQL SELECT statement that is not encapsulated in the MAX function, you must use the SQL GROUP BY clause. The department field must, therefore, be listed in the GROUP BY section.

Frequently Asked Questions

Question: I’m trying to pull some info out of a table. To simplify, let’s say the table (report_history) has 4 columns: user_name, report_job_id, report_name, and report_run_date.

Each time a report is run in Oracle, a record is written to this table noting the above info. What I am trying to do is pull from this table when the last time each distinct report was run and who ran it last.

My initial query:

SELECT report_name, MAX(report_run_date)
FROM report_history
GROUP BY report_name

runs fine. However, it does not provide the name of the user who ran the report.

Adding user_name to both the select list and to the group by clause returns multiple lines for each report; the results show the last time each person ran each report in question. (i.e. User1 ran Report 1 on 01-JUL-03, User2 ran Report1 on 01-AUG-03). I don’t want that….I just want to know who ran a particular report the last time it was run.

Any suggestions?

Answer: This is where things get a bit complicated. The SQL SELECT statement below will return the results that you want:

SELECT rh.user_name, rh.report_name, rh.report_run_date
FROM report_history rh,
  (SELECT MAX(report_run_date) AS maxdate, report_name
   FROM report_history
   GROUP BY report_name) maxresults
WHERE rh.report_name = maxresults.report_name
AND rh.report_run_date= maxresults.maxdate;

Let’s take a few moments to explain what we’ve done.

First, we’ve aliased the first instance of the report_history table as rh.

Second, we’ve included two components in our FROM clause. The first is the table called report_history (aliased as rh). The second is a select statement:

(SELECT MAX(report_run_date) AS maxdate, report_name
 FROM report_history
 GROUP BY report_name) maxresults

We’ve aliased the max(report_run_date) as maxdate and we’ve aliased the entire result set as maxresults.

Now, that we’ve created this select statement within our FROM clause, Oracle will let us join these results against our original report_history table. So we’ve joined the report_name and report_run_date fields between the tables called rh and maxresults. This allows us to retrieve the report_name, max(report_run_date) as well as the user_name.


Question: I need help with a SQL query. I have a table in Oracle called orders which has the following fields: order_no, customer, and amount.

I need a query that will return the customer who has ordered the highest total amount.

Answer: The following SQL should return the customer with the highest total amount in the orders table.

SELECT query1.*
FROM (SELECT customer, SUM(orders.amount) AS total_amt
      FROM orders
      GROUP BY orders.customer) query1,

     (SELECT MAX(query2.total_amt) AS highest_amt
      FROM (SELECT customer, SUM(orders.amount) AS total_amt
            FROM orders
            GROUP BY orders.customer) query2) query3
WHERE query1.total_amt = query3.highest_amt;

This SQL SELECT statement will summarize the total orders for each customer and then return the customer with the highest total orders. This syntax is optimized for Oracle and may not work for other database technologies.


Question: I’m trying to retrieve some info from an Oracle database. I’ve got a table named Scoring with two fields – Name and Score. What I want to get is the highest score from the table and the name of the player.

Answer: The following SQL SELECT statement should work:

SELECT Name, Score
FROM Scoring
WHERE Score = (SELECT MAX(Score) FROM Scoring);

Question: I need help in a SQL query. I have a table in Oracle called cust_order which has the following fields: OrderNo, Customer_id, Order_Date, and Amount.

I would like to find the customer_id, who has Highest order count.

I tried with following query.

SELECT MAX(COUNT(*))
FROM CUST_ORDER
GROUP BY CUSTOMER_ID;

This gives me the max Count, But, I can’t get the CUSTOMER_ID. Can you help me please?

Answer: The following SQL SELECT statement should return the customer with the highest order count in the cust_order table.

SELECT query1.*
FROM (SELECT Customer_id, Count(*) AS order_count
      FROM cust_order
      GROUP BY cust_order.Customer_id) query1,

     (SELECT max(query2.order_count) AS highest_count
      FROM (SELECT Customer_id, Count(*) AS order_count
            FROM cust_order
            GROUP BY cust_order.Customer_id) query2) query3
WHERE query1.order_count = query3.highest_count;

This SQL SELECT statement will summarize the total orders for each customer and then return the customer with the highest order count. This syntax is optimized for Oracle and may not work for other database technologies.


Question: I’m trying to get the employee with the maximum salary from department 30, but I need to display the employee’s full information. I’ve tried the following query, but it returns the result from both department 30 and 80:

SELECT *
FROM employees
WHERE salary = (SELECT MAX(salary)
                FROM employees
                WHERE department_id=30);

Answer: The SQL SELECT statement that you have written will first determine the maximum salary for department 30, but then you select all employees that have this salary. In your case, you must have 2 employees (one in department 30 and another in department 80) that have this same salary. You need to make sure that you are refining your query results to only return employees from department 30.

Try using this SQL SELECT statement:

SELECT *
FROM employees
WHERE department_id=30
AND salary = (SELECT MAX(salary)
              FROM employees
              WHERE department_id=30);

This will return the employee information for only the employee in department 30 that has the highest salary.

В этом учебном материале вы узнаете, как использовать SQL функцию MAX с синтаксисом примерами.

Описание

SQL функция MAX используется для возврата максимального значения выражения в операторе SELECT.

Синтаксис

Синтаксис для функции MAX в SQL.

SELECT MAX(aggregate_expression)
FROM tables
[WHERE conditions];

Или синтаксис для функции MAX при группировке результатов по одному или нескольким столбцам.

SELECT expression1, expression2, … expression_n,
MAX(aggregate_expression)
FROM tables
[WHERE conditions]
GROUP BY expression1, expression2, … expression_n;

Параметры или аргумент

expression1, expression2, … expression_n
Выражения, которые не инкапсулированы в функцию MAX и должны быть включены в предложение GROUP BY в конце SQL запроса
aggregate_expression
Это столбец или выражение, из которого будет возвращено максимальное значение
tables
Таблицы, из которых вы хотите получить записи. В предложении FROM должна быть указана хотя бы одна таблица
WHERE conditions
Необязательный. Это условия, которые должны быть выполнены для выбора записей

Пример – с одним выражение

Простейшим способом использования SQL функции MAX будет возвращение одного поля, которое вычисляет значение MAX.
Например, вы можете узнать максимальную зарплату всех сотрудников.

SELECT MAX(salary) AS “Highest salary”

  FROM employees;

В этом примере SQL функции MAX мы выражению MAX(salary) указали псевдоним “Highest salary”. В результате “Highest salary” будет отображаться как имя поля при возврате набора результатов.

Пример – использование SQL оператора GROUP BY

В некоторых случаях вам потребуется использовать SQL оператор GROUP BY с функцией SQL MAX.
Например, вы также можете использовать SQL функцию MAX, чтобы вернуть название каждого отдела и максимальную зарплату в отделе.

SELECT department, MAX(salary) AS “Highest salary”

  FROM employees

GROUP BY department;

Поскольку в SQL операторе SELECT вы указали один столбец, который не инкапсулирован в функции MAX, вы должны использовать SQL оператор GROUP BY. Поэтому поле department должно быть указано в разделе GROUP BY.

Оператор SQL MAX() — функция возвращающая максимальное значение столбца таблицы.

Функция SQL MAX() имеет следующий синтаксис:

MAX(column_name)

Примеры оператора SQL MAX: Имеется следующая таблица Universities:

ID UniversityName Students Faculties Professores Location Site
1 Perm State National Research University 12400 12 1229 Perm psu.ru
2 Saint Petersburg State University 21300 24 13126 Saint-Petersburg  spbu.ru
3 Novosibirsk State University 7200 13 1527 Novosibirsk nsu.ru
4 Moscow State University 35100 39 14358 Moscow msu.ru
5 Higher School of Economics 20335 12 1615 Moscow hse.ru
6 Ural Federal University 57000 19 5640 Yekaterinburg urfu.ru
7 National Research Nuclear University 8600 10 936 Moscow mephi.ru

Пример 1: Используя оператор SQL MAX найти максимальное значение колонки Students:

SELECT MAX(Students)
FROM Univerities

Ответ: 57000

Пример 2: Используя оператор SQL MAX найти максимальное значение колонки Faculties, где расположение университета (Location) — Saint-Petersburg:

SELECT MAX(Faculties)
FROM Universities
WHERE Location = 'Saint-Petersburg'

Ответ: 24

Пример 3: Используя оператор SQL MAX найти университет (UniversityName) с наибольшим числом преподавателей (Professores):

SELECT UniversityName
FROM University
WHERE Professores = (SELECT MAX(Professores) FROM Universities)

Ответ: Moscow State University

title description author ms.author ms.date ms.service ms.subservice ms.topic f1_keywords helpviewer_keywords dev_langs monikerRange

MAX (Transact-SQL)

MAX (Transact-SQL)

markingmyname

maghan

08/23/2017

sql

t-sql

reference

MAX

MAX_TSQL

MAX function [Transact-SQL]

values [SQL Server], maximum

maximum values [SQL Server]

TSQL

>= aps-pdw-2016 || = azuresqldb-current || = azure-sqldw-latest || >= sql-server-2016 || >= sql-server-linux-2017 || = azuresqldb-mi-current

MAX (Transact-SQL)

[!INCLUDE sql-asdb-asdbmi-asa-pdw]

Returns the maximum value in the expression.

:::image type=”icon” source=”../../includes/media/topic-link-icon.svg” border=”false”::: Transact-SQL syntax conventions

Syntax

-- Aggregation Function Syntax  
MAX( [ ALL | DISTINCT ] expression )  
  
-- Analytic Function Syntax  
MAX ([ ALL ] expression) OVER ( <partition_by_clause> [ <order_by_clause> ] )  

[!INCLUDEsql-server-tsql-previous-offline-documentation]

Arguments

ALL
Applies the aggregate function to all values. ALL is the default.

DISTINCT
Specifies that each unique value is considered. DISTINCT is not meaningful with MAX and is available for ISO compatibility only.

expression
Is a constant, column name, or function, and any combination of arithmetic, bitwise, and string operators. MAX can be used with numeric, character, uniqueidentifier, and datetime columns, but not with bit columns. Aggregate functions and subqueries are not permitted.

For more information, see Expressions (Transact-SQL).

OVER ( partition_by_clause [ order_by_clause ] )
partition_by_clause divides the result set produced by the FROM clause into partitions to which the function is applied. If not specified, the function treats all rows of the query result set as a single group. order_by_clause determines the logical order in which the operation is performed. partition_by_clause is required. For more information, see OVER Clause (Transact-SQL).

Return Types

Returns a value same as expression.

Remarks

MAX ignores any null values.

MAX returns NULL when there is no row to select.

For character columns, MAX finds the highest value in the collating sequence.

MAX is a deterministic function when used without the OVER and ORDER BY clauses. It is nondeterministic when specified with the OVER and ORDER BY clauses. For more information, see Deterministic and Nondeterministic Functions.

Examples

A. Simple example

The following example returns the highest (maximum) tax rate in the [!INCLUDEssSampleDBnormal] database.

SELECT MAX(TaxRate)  
FROM Sales.SalesTaxRate;  
GO  

[!INCLUDEssResult]

-------------------  
19.60  
Warning, null value eliminated from aggregate.  
 
(1 row(s) affected)  

B. Using the OVER clause

The following example uses the MIN, MAX, AVG, and COUNT functions with the OVER clause to provide aggregated values for each department in the HumanResources.Department table in the [!INCLUDEssSampleDBnormal] database.

SELECT DISTINCT Name  
       , MIN(Rate) OVER (PARTITION BY edh.DepartmentID) AS MinSalary  
       , MAX(Rate) OVER (PARTITION BY edh.DepartmentID) AS MaxSalary  
       , AVG(Rate) OVER (PARTITION BY edh.DepartmentID) AS AvgSalary  
       ,COUNT(edh.BusinessEntityID) OVER (PARTITION BY edh.DepartmentID) AS EmployeesPerDept  
FROM HumanResources.EmployeePayHistory AS eph  
JOIN HumanResources.EmployeeDepartmentHistory AS edh  
     ON eph.BusinessEntityID = edh.BusinessEntityID  
JOIN HumanResources.Department AS d  
 ON d.DepartmentID = edh.DepartmentID  
WHERE edh.EndDate IS NULL  
ORDER BY Name;  

[!INCLUDEssResult]

Name                          MinSalary             MaxSalary             AvgSalary             EmployeesPerDept  
----------------------------- --------------------- --------------------- --------------------- ----------------  
Document Control              10.25                 17.7885               14.3884               5  
Engineering                   32.6923               63.4615               40.1442               6  
Executive                     39.06                 125.50                68.3034               4  
Facilities and Maintenance    9.25                  24.0385               13.0316               7  
Finance                       13.4615               43.2692               23.935                10  
Human Resources               13.9423               27.1394               18.0248               6  
Information Services          27.4038               50.4808               34.1586               10  
Marketing                     13.4615               37.50                 18.4318               11  
Production                    6.50                  84.1346               13.5537               195  
Production Control            8.62                  24.5192               16.7746               8  
Purchasing                    9.86                  30.00                 18.0202               14  
Quality Assurance             10.5769               28.8462               15.4647               6  
Research and Development      40.8654               50.4808               43.6731               4  
Sales                         23.0769               72.1154               29.9719               18  
Shipping and Receiving        9.00                  19.2308               10.8718               6  
Tool Design                   8.62                  29.8462               23.5054               6  
  
 (16 row(s) affected)  

C. Using MAX with character data

The following example returns the database name that sorts as the last name alphabetically. The example uses WHERE database_id < 5, to consider only the system databases.

SELECT MAX(name) FROM sys.databases WHERE database_id < 5;

The last system database is tempdb.

See Also

Aggregate Functions (Transact-SQL)
OVER Clause (Transact-SQL)

Добавить комментарий