Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
173 views
in Technique[技术] by (71.8m points)

sql - Select all the data from a table where the timestamp against each customer_id is maximum

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"
question from:https://stackoverflow.com/questions/65851148/select-all-the-data-from-a-table-where-the-timestamp-against-each-customer-id-is

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
                      );

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...