Monday, April 21, 2014

TSQL Tutorial: MAX Function

The TSQL MAX function is used to return the maximum value of an expression in a SELECT statement. The syntax for the TSQL MAX function is:

SELECT MAX(expression)
FROM tables
WHERE conditions;

For example you want to get highest salary from salary column. It means it will be the highest salary given to any employee in the company


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

MAX with TSQL GROUP BY


MAX can be used for a group also. In that case max will return maximum value of a group.

For example, you could also use the TSQL 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 TSQL SELECT statement that is not encapsulated in the MAX function, you must use the TSQL GROUP BY clause. The department field must, therefore, be listed in the GROUP BY section. 

No comments:

Post a Comment