The data is as follows and each cust_id (customer id) may or may not have multiple rows of data. Just as a sample data I have created the following. I want to write a SQL query to get all the data of each cust_id (customer id) where the timestamp is latest.
Cust_id | name | visit_date |
---|---|---|
1 | "AB" | "2000-01-22 21:00:00.000000" |
1 | "AB1" | "2000-01-22 22:00:00.000000" |
2 | "MN" | "2000-01-22 22:00:00.000000" |
2 | "MN1" | "2000-01-22 21:00:00.000000" |
3 | "XY" | "2000-01-22 22:00:00.000000" |
3 | "XY1" | "2000-01-22 21:00:00.000000" |
4 | "HI" | "2000-01-22 21:00:00.000000" |
A canonical method is:
select te.*
from time_entry te
where te.visit_date = (select max(te2.visit_date)
from time_entry te2
where te2.cust_id = te.cust_id
);
SELECT * FROM time_entry
WHERE visit_date IN(SELECT MAX(visit_date) FROM time_entry
GROUP BY cust_id)
ORDER BY cust_id;
The above query worked for me but I am not sure of using a group by without selecting any other column with the aggregate function.
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.