0

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

8
  • 1
    I'm not seeing the logic by which you pull out the (Rafael, 5, 2018) record. Can you explain the logic behind your intended query? Commented Sep 6, 2018 at 10:53
  • Shouldn't you be wanting (Rafael,9,2018)? Commented Sep 6, 2018 at 10:54
  • @SEarle1986 my bad, sorry Commented Sep 6, 2018 at 10:55
  • by the way if you sum 9 + 2018 or 10 + 2017 the results are the same! Commented Sep 6, 2018 at 10:56
  • What do you want is not so clear, so, maybe you are looking at this query: SELECT TOP 1 * FROM records Commented Sep 6, 2018 at 10:58

3 Answers 3

2

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
Sign up to request clarification or add additional context in comments.

4 Comments

this is a nice variant but i prefer to use TOP. becuase I'm pretty sure he wants the top 1 and not the highest year and month combo. But the PO is not so clear about what he wants. upvote for you!
i prefer to use TOP... the TOP clause works on MSSQL server. @Simo
LIMIT 1 == TOP 1
@SEarle1986 i know
2

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.

2 Comments

need to add DESC in order by
People will have downvoted because the answer was incorrect. You're supposed to follow up a downvote with a comment. I held back from the vote and just made the comment
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.