I have following table ContactDetails
. This table contains both cell phone as well as emails. These rows can be updated based on Users latest contact details. So userid
(here 1) can have multiple rows grouped by Email and cell as below. There can be multiple users 2.3.4...so on
Rows are as below
SrNo Userid ContactType ContactDetail LoadDate
1 1 Email x1.y@gmail.com 2013-01-01
2 1 Cell 12345678 2013-01-01
3 1 Email x2.y@gmail.com 2012-01-01
4 1 Cell 98765432 2012-01-01
5 1 Email x2.y@gmail.com 2011-01-01
6 1 Cell 987654321 2011-01-01
I am looking for recent Email
and Cell
details of users. I tried running the query as below
Select
Userid,
Max(ContactDetail),
MAX(LoadDate)
from
ContactDetails
group by
Userid, ContactType;
But I understand that this won't work.
Can anyone give some suggestion to pull the latest email and cell in single or sub-queries?
Cheers! Junni
You can use ROW_NUMBER()
to select the most recent row of interest:
;With Ordered as (
select UserId,ContactType,ContactDetail,LoadDate,
ROW_NUMBER() OVER (
PARTITION BY UserID,ContactType
ORDER BY LoadDate DESC) as rn
from ContactDetails
)
select * from Ordered where rn = 1
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.