简体   繁体   中英

MySQL Return all unique values in a column along with the last date associated with each

I have a table relative from which I am trying to pull all the unique ID s as well as the first and last date associated with each one. So far, I have the query below, which returns each unique ID along with the first date in the table associated with each ID . How could I modify this query (or run a second one) that would return each unique ID along with the last date in the table associated with that ID ?

SELECT  `ID`, `Date` FROM `relative`.`datatable` GROUP BY `ID`

This is a basic aggregation query:

SELECT  `ID`, min(`Date`), max(`date`)
FROM `relative`.`datatable`
GROUP BY `ID`;

And, as @rogoas points out, your query is not guaranteed to return the minimum date. It will return an arbitrary date for each id.

You can try this with min(date) and max(date) :-

SELECT  `ID`, min(`Date`), max(`date`) FROM `relative`.`datatable`
GROUP BY `ID`;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM