More Technical Example
Let’s create the table and insert some data inside it. The following query creates a SALES table and inserts three records in it.
Query:
-- create
CREATE TABLE SALES (
product_name VARCHAR(20),
jan INT,
feb INT,
mar INT
);
-- insert
INSERT INTO SALES VALUES ('Book', 123, 89, 22);
INSERT INTO SALES VALUES ('Pen', 99, 12, 51);
INSERT INTO SALES VALUES ('Sharpner', 82, 47, 90);
--to show the table
SELECT * FROM SALES;
Output:
Explanation: The above table contains the information about different products and the number of units sold in January, February, and March. So, the record (‘Book’, 123, 89, 22) states that 123 units, 89 units, and 22 units of the book was sold in January, February, and March respectively.
Now we will find out what the maximum unit of a product sold in any of the three months for all the products in the table. For this we are going to make use of the GREATEST() function we understood in method 2. As already mentioned, we can use GREATEST() function to find maximum value from more than 2 values. The following query makes use of GREATEST() function to find the maximum units sold for each product.
Query:
SELECT
product_name,
GREATEST(jan, feb, mar) AS max_sales
FROM
SALES;
Output:
Explanation: As we can see that books were sold maximum number of 123 units, pens were sold maximum number of 99 units, and sharpeners were sold maximum number of 90 units.
How to Find the Maximum of Multiple Columns in SQL Server?
When working with SQL Server databases, there are times when we need to find the maximum value among multiple columns. This task can be accomplished using various techniques within SQL queries. By using functions like CASE
and GREATEST
, SQL Server provides efficient ways to determine the maximum value among several columns in a table. In this article, we will explore these methods in detail, offering insights into how to effectively find the maximum value across multiple columns in SQL Server.