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
158 views
in Technique[技术] by (71.8m points)

sql - Get max dates for each customer

Let's say I have a customer table like so:

id | start_date | created_at
-----------------------------
1  | 2020-1-15  | 2020-1-15
1  | 2020-1-16  | 2020-1-15
1  | 2020-1-16  | 2020-1-16
2  | 2020-1-15  | 2020-1-15
2  | 2020-1-16  | 2020-1-15

I want to get 1 row per customer id that has the max(start_date) and if it's the same date will use the max(created_at).

Result should look like this:

id | start_date | created_at
-----------------------------
1  | 2020-1-16  | 2020-1-16
2  | 2020-1-16  | 2020-1-15

I'm having a hard time with window functions as I thought a partition by id would work but I have 2 dates. Maybe I use a group by?

question from:https://stackoverflow.com/questions/65926854/get-max-dates-for-each-customer

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

1 Reply

0 votes
by (71.8m points)

please try this one, you could use order by two columns

SELECT * FROM (
SELECT id, start_date, Created_At, ROW_NUMBER()OVER(PARTITION BY id ORDER BY start_date DESC, Created_At DESC) AS R
FROM #date
) A
WHERE A.R = 1

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

...