How can I get the oldest entry (month-year) using month and year table column (int) in mysql?

Rodrick :

I have a table with a column that keeps the year and anoher column that keep the month. How can I get the oldest date (minimun td_month-td_year) grouping by son_id? Considerations: table_id could be not in order

CREATE TABLE mytable (
table_id INT,  
father_id INT, 
son_id INT, 
mt_month INT, 
mt_year INT);

INSERT INTO mytable VALUES
("101","11","370","12","2013"),
("102","11","370","1","2014"),
("103","11","371","2","2015"),
("105","11","371","11","2008"),
("107","11","371","12","2008"),
("108","11","372","2","2009"),
("109","11","372","3","2009"),
("111","11","372","12","2009"),
("113","11","373","1","2013"),
("115","11","373","11","2017"),
("117","11","373","11","2011"),
("119","11","373","12","2012");

This query will get wrong month not considering the year:

select son_id, min(mt_month), min(mt_year) from mytable group by son_id;

https://www.db-fiddle.com/f/v1Xty9c1SAp2PfaWCC4WvK/3

Should I use concat mt_month and mt_year and transform it in date format?

PeterHe :

You need to get the min year first:

SELECT y.son_id,y.min_year,min(t.mt_month) AS min_month
FROM mytable t
INNER JOIN (
  select son_id,  min(mt_year) AS min_year from mytable group by son_id) y
ON t.son_id=y.son_id
AND t.mt_year=y.min_year
GROUP BY y.son_id,y.min_year;

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=13947&siteId=1