Home > Database > Mysql Tutorial > How to Find the Maximum Value Across Multiple Columns in a SQL Query?

How to Find the Maximum Value Across Multiple Columns in a SQL Query?

Linda Hamilton
Release: 2025-01-21 22:35:10
Original
167 people have browsed it

How to Find the Maximum Value Across Multiple Columns in a SQL Query?

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template