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

How to Find the Maximum Date Across Multiple Columns in SQL?

Linda Hamilton
Release: 2025-01-21 22:42:11
Original
856 people have browsed it

How to Find the Maximum Date Across Multiple Columns in SQL?

Returning the maximum value of multiple columns in SQL

Suppose you have a table named "TableName" in your database with the following columns:

  • Number
  • Date1
  • Date2
  • Date3
  • Cost

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

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:

  • Number
  • Most_Recent_Date
  • Cost

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!

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