Get the maximum value of multiple columns in SQL query
When dealing with tables containing multiple date or numeric columns, it is often necessary to retrieve the maximum value for each row. Consider a table named "TableName" which contains columns "Number", "Date1", "Date2", "Date3" and "Cost". The goal is to retrieve a new table containing the columns "Number", "Most_Recent_Date" and "Cost", where "Most_Recent_Date" contains the maximum value of the "Date1", "Date2" and "Date3" columns.
Solution using T-SQL and SQL Server
An efficient way to achieve this result is to use the following T-SQL query:
<code class="language-sql">SELECT [其他字段], (SELECT Max(v) FROM (VALUES (date1), (date2), (date3),...) AS value(v)) as [MaxDate] FROM [您的表名]</code>
In this query, the table value constructor "VALUES" is used to construct a list of values from the "date1", "date2" and "date3" columns. The Max() function is then applied to this list to determine the maximum value and assign it to the "MaxDate" column. "Additional fields" refers to any other required columns in the query to be included in the output table.
By implementing this solution, you can efficiently retrieve the maximum value for each row of a specified column in the "TableName" table.
The above is the detailed content of How to Find the Maximum Value Across Multiple Columns in a SQL Query?. For more information, please follow other related articles on the PHP Chinese website!