[英]Get max value and max date from sql query
I have a table with duplicate member names but these duplicates also have more than one date and a specific ID.我有一个成员名称重复的表,但这些重复项也有多个日期和特定 ID。 I want the row of the member name with the most recent date (because a member could have been called more than one time a day) and biggest CallID number.
我想要具有最近日期的成员名称行(因为成员每天可能被调用多次)和最大的 CallID 号码。
MemberID FirstName LastName CallDate CallID
0123 Carl Jones 2019-03-01 123456
0123 Carl Jones 2020-10-12 215789
0123 Carl Jones 2020-10-12 312546
2045 Sarah Marty 2021-05-09 387945
2045 Sarah Marty 2021-08-11 398712
4025 Jane Smith 2021-10-18 754662
4025 Jane Smith 2021-11-03 761063
8282 Suzy Aaron 2019-12-12 443355
8282 Suzy Aaron 2019-12-12 443386
So the desired output from this table would be所以这个表的期望输出是
MemberID FirstName LastName CallDate CallID
0123 Carl Jones 2020-10-12 312546
2045 Sarah Marty 2021-08-11 398712
4025 Jane Smith 2021-11-03 761063
8282 Suzy Aaron 2019-12-12 443386
The query I've tried is我试过的查询是
SELECT DISTINCT MemberID, FirstName, LastName, MAX(CallDate) as CallDate, MAX(CallID) as CallID
FROM dbo.table
GROUP BY MemberID, FirstName, LastName, CallDate, CallID
ORDER BY LastName asc;
But I'm still getting duplicate names with all their calldates and CallID但我仍然收到了重复的名字以及他们所有的通话日期和 CallID
try removing CallDate, CallID from the group by clause.尝试从 group by 子句中删除 CallDate、CallID。
So :所以 :
SELECT MemberID, FirstName, LastName, MAX(CallDate) as CallDate, MAX(CallID) as CallID
FROM dbo.table
GROUP BY MemberID, FirstName, LastName
ORDER BY LastName asc;
Hopefully that should do it.希望应该这样做。
you can use window function:您可以使用窗口函数:
select * from (
select * , row_number() over (partition by MemberID order by CallID desc) rn
from tablename
) t where rn = 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.