Rafáel Vrn
Rafáel Vrn

Reputation: 11

SQL: MAX of summing the values of 2 columns

so I have a table "records" like this:

name     month     year
Rafael   9         2018
Rafael   5         2018
Rafael   10        2017

And I want to get my last records (Rafael, 9, 2018). I thought about summing the month and the year and getting the max of that sum like this:

select * from records, max(month + year) as max_date

But doesn't seem to be right. Thanks for help

Upvotes: 0

Views: 58

Answers (3)

Zaynul Abadin Tuhin
Zaynul Abadin Tuhin

Reputation: 31993

Use concat if you want to concat max month and max year

    Select name ,concat (concat( max(month), '-'),max(year)) from records
    Group by name

but if you want just year wise max year date information then use below

Select * from records
     order by year desc
     limit 1

https://www.db-fiddle.com/f/sqQz1WEEAukoWEWkbxBYxe/0

name    month   year
Rafael   9      2018

Upvotes: 0

tardis
tardis

Reputation: 1360

Do you mean the output of the follwing?

select *
from records
order by year desc, month desc
limit 1

In general, it would be more useful to use one DATE or DATETIME column type for this purpose where you can extract year and month if you want.

Upvotes: 2

Madhur Bhaiya
Madhur Bhaiya

Reputation: 28834

Using ORDER BY clause, you can get the highest year and month combo. Try the following:

SELECT *
FROM records
ORDER BY year DESC, month DESC
LIMIT 1

Upvotes: 2

Related Questions