MAX (Transact-SQL)MAX (Transact-SQL)
Aplica-se a:Applies to: SQL ServerSQL Server (todas as versões compatíveis)
SQL ServerSQL Server (all supported versions)
Banco de Dados SQL do AzureAzure SQL Database
Banco de Dados SQL do AzureAzure SQL Database
Instância Gerenciada do Azure SQLAzure SQL Managed Instance
Instância Gerenciada do Azure SQLAzure SQL Managed Instance
Azure Synapse AnalyticsAzure Synapse Analytics
Azure Synapse AnalyticsAzure Synapse Analytics
Parallel Data WarehouseParallel Data Warehouse
Parallel Data WarehouseParallel Data Warehouse
SQL ServerSQL Server (todas as versões compatíveis)
SQL ServerSQL Server (all supported versions)
Banco de Dados SQL do AzureAzure SQL Database
Banco de Dados SQL do AzureAzure SQL Database
Instância Gerenciada do Azure SQLAzure SQL Managed Instance
Instância Gerenciada do Azure SQLAzure SQL Managed Instance
Azure Synapse AnalyticsAzure Synapse Analytics
Azure Synapse AnalyticsAzure Synapse Analytics
Parallel Data WarehouseParallel Data Warehouse
Parallel Data WarehouseParallel Data Warehouse
Retorna o valor máximo na expressão.Returns the maximum value in the expression.
Convenções da sintaxe Transact-SQL
Transact-SQL Syntax Conventions
SintaxeSyntax
-- Aggregation Function Syntax
MAX( [ ALL | DISTINCT ] expression )
-- Analytic Function Syntax
MAX ([ ALL ] expression) OVER ( [ <partition_by_clause> ] [ <order_by_clause> ] )
Observação
Para ver a sintaxe do Transact-SQL para o SQL Server 2014 e versões anteriores, confira a Documentação das versões anteriores.To view Transact-SQL syntax for SQL Server 2014 and earlier, see Previous versions documentation.
ArgumentosArguments
ALLALL
Aplica a função de agregação a todos os valores.Applies the aggregate function to all values. ALL é o padrão.ALL is the default.
DISTINTODISTINCT
Especifica que cada valor exclusivo é considerado.Specifies that each unique value is considered. DISTINCT não é significativo com MAX e está disponível somente para compatibilidade com ISO.DISTINCT is not meaningful with MAX and is available for ISO compatibility only.
expressãoexpression
É uma constante, nome de coluna ou função e qualquer combinação de operadores aritméticos, bit a bit e de cadeia de caracteres.Is a constant, column name, or function, and any combination of arithmetic, bitwise, and string operators. MAX pode ser usado com colunas numeric, character, uniqueidentifier e datetime, mas não com colunas bits.MAX can be used with numeric, character, uniqueidentifier, and datetime columns, but not with bit columns. Funções de agregação e subconsultas não são permitidas.Aggregate functions and subqueries are not permitted.
Para obter mais informações, veja Expressões (Transact-SQL).For more information, see Expressions (Transact-SQL).
OVER ( [ partition_by_clause ] order_by_clause )OVER ( [ partition_by_clause ] order_by_clause)
partition_by_clause divide o conjunto de resultados produzido pela cláusula FROM em partições às quais a função é aplicada.partition_by_clause divides the result set produced by the FROM clause into partitions to which the function is applied. Se não for especificado, a função tratará todas as linhas do conjunto de resultados da consulta como um único grupo.If not specified, the function treats all rows of the query result set as a single group. order_by_clause determina a ordem lógica na qual a operação é executada.order_by_clause determines the logical order in which the operation is performed. order_by_clause é obrigatório.order_by_clause is required. Para obter mais informações, consulte Cláusula OVER (Transact-SQL).For more information, see OVER Clause (Transact-SQL).
Tipos de retornoReturn Types
Retorna um valor igual a expression.Returns a value same as expression.
ComentáriosRemarks
MAX ignora quaisquer valores nulos.MAX ignores any null values.
MAX retornará NULL quando não houver linha a ser selecionada.MAX returns NULL when there is no row to select.
Para colunas de caracteres, MAX localiza o valor mais alto na sequência de agrupamento.For character columns, MAX finds the highest value in the collating sequence.
MAX é uma função determinística quando usada sem as cláusulas OVER e ORDER BY.MAX is a deterministic function when used without the OVER and ORDER BY clauses. É não determinística quando especificada com as cláusulas OVER e ORDER BY.It is nondeterministic when specified with the OVER and ORDER BY clauses. Para obter mais informações, veja Funções determinísticas e não determinísticas.For more information, see Deterministic and Nondeterministic Functions.
ExemplosExamples
a.A. Exemplo simplesSimple example
O exemplo a seguir retorna a taxa de imposto mais alta (máxima) no banco de dados AdventureWorks2012AdventureWorks2012.The following example returns the highest (maximum) tax rate in the AdventureWorks2012AdventureWorks2012 database.
SELECT MAX(TaxRate)
FROM Sales.SalesTaxRate;
GO
Este é o conjunto de resultados.Here is the result set.
-------------------
19.60
Warning, null value eliminated from aggregate.
(1 row(s) affected)
B.B. Usando a cláusula OVERUsing the OVER clause
O exemplo a seguir usa as funções MIN, MAX, AVG e COUNT com a cláusula OVER para fornecer valores agregados para cada departamento na tabela HumanResources.Department
no banco de dados AdventureWorks2012AdventureWorks2012.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 AdventureWorks2012AdventureWorks2012 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;
Este é o conjunto de resultados.Here is the result set.
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.C. Usando MAX com os dados de caractereUsing MAX with character data
O exemplo a seguir retorna o nome do banco de dados que classifica como o último nome em ordem alfabética.The following example returns the database name that sorts as the last name alphabetically. O exemplo usa WHERE database_id < 5
, para considerar somente os bancos de dados do sistema.The example uses WHERE database_id < 5
, to consider only the system databases.
SELECT MAX(name) FROM sys.databases WHERE database_id < 5;
O último banco de dados do sistema é tempdb
.The last system database is tempdb
.
Consulte TambémSee Also
Funções de agregação (Transact-SQL) Aggregate Functions (Transact-SQL)
Cláusula OVER (Transact-SQL)OVER Clause (Transact-SQL)