Returning the maximum value of multiple columns in SQL
Suppose you have a table named "TableName" in your database with the following columns:
Your goal is to retrieve a result set that displays the maximum value of the "Date" column for each row. You also need to include the "Number" and "Cost" columns.
Solution
You can achieve this result by using the MAX() function in conjunction with the VALUES table value constructor. Here is the updated query:
<code class="language-sql">SELECT Number, (SELECT MAX(v) FROM (VALUES (Date1), (Date2), (Date3)) AS value(v)) AS Most_Recent_Date, Cost FROM TableName;</code>
Explanation
The subquery in the MAX() function uses the VALUES table value constructor to create a temporary table containing the "Date" column value. Then, the MAX() function selects the maximum value from this temporary table.
The results will be displayed in the desired format:
The above is the detailed content of How to Find the Maximum Date Across Multiple Columns in SQL?. For more information, please follow other related articles on the PHP Chinese website!