📜  sql max of two values - SQL (1)

📅  最后修改于: 2023-12-03 15:05:17.211000             🧑  作者: Mango

SQL Max of Two Values

As a programmer, you may need to get the maximum value of two columns or expressions in SQL. In this case, you can use the MAX() function to achieve this.

The syntax is as follows:

SELECT MAX(column1, column2) AS max_value
FROM table_name;

where column1 and column2 are the names of columns or expressions whose maximum value you want to get, and table_name is the name of the table containing these columns.

For example, let's say we have a table named sales with the following data:

| id | product | price1 | price2 | |----|---------|--------|--------| | 1 | A | 10 | 15 | | 2 | B | 20 | 18 | | 3 | C | 12 | 12 |

If we want to get the maximum price for each product, we can use the following query:

SELECT product, MAX(price1, price2) AS max_price
FROM sales
GROUP BY product;

This will return the following result:

| product | max_price | |---------|-----------| | A | 15 | | B | 20 | | C | 12 |

Note that the GROUP BY clause is used since we want to get the maximum value for each product.

In conclusion, the MAX() function is a very useful tool in SQL when you need to get the maximum value of two or more columns or expressions.