gpt4 book ai didi

TSQL 选择最大值

转载 作者:行者123 更新时间:2023-12-04 23:07:02 25 4
gpt4 key购买 nike

Userid   FirstName   LastName        UserUpdate 
1 Dan Kramer 1/1/2005
1 Dan Kramer 1/1/2007
1 Dan Kramer 1/1/2009
2 Pamella Slattery 1/1/2005
2 Pam Slattery 1/1/2006
2 Pam Slattery 1/1/2008
3 Samamantha Cohen 1/1/2008
3 Sam Cohen 1/1/2009

我需要为所有这些用户提取最新更新,基本上这就是我要找的:
Userid   FirstName   LastName        UserUpdate  
1 Dan Kramer 1/1/2009
2 Pam Slattery 1/1/2008
3 Sam Cohen 1/1/2009

现在,当我运行以下命令时:

SELECT Userid, FirstName, LastName, Max(UserUpdate) AS MaxDate
发件人表
GROUP BY Userid, FirstName, LastName

我仍然得到重复,像这样:
Userid   FirstName   LastName        UserUpdate 
1 Dan Kramer 1/1/2009
2 Pamella Slattery 1/1/2005
2 Pam Slattery 1/1/2008
3 Samamantha Cohen 1/1/2008
3 Sam Cohen 1/1/2009

最佳答案

尝试:

declare @Table table (userid int,firstname varchar(10),lastname varchar(20), userupdate datetime)
INSERT @Table VALUES (1, 'Dan' ,'Kramer' ,'1/1/2005')
INSERT @Table VALUES (1, 'Dan' ,'Kramer' ,'1/1/2007')
INSERT @Table VALUES (1, 'Dan' ,'Kramer' ,'1/1/2009')
INSERT @Table VALUES (2, 'Pamella' ,'Slattery' ,'1/1/2005')
INSERT @Table VALUES (2, 'Pam' ,'Slattery' ,'1/1/2006')
INSERT @Table VALUES (2, 'Pam' ,'Slattery' ,'1/1/2008')
INSERT @Table VALUES (3, 'Samamantha' ,'Cohen' ,'1/1/2008')
INSERT @Table VALUES (3, 'Sam' ,'Cohen' ,'1/1/2009')

SELECT
dt.Userid,dt.MaxDate
,MIN(a.FirstName) AS FirstName, MIN(a.LastName) AS LastName
FROM (SELECT
Userid, Max(UserUpdate) AS MaxDate
FROM @Table GROUP BY Userid
) dt
INNER JOIN @Table a ON dt.Userid=a.Userid and dt.MaxDate =a.UserUpdate
GROUP BY dt.Userid,dt.MaxDate

输出:
Userid      MaxDate                 FirstName  LastName
----------- ----------------------- ---------- --------------------
1 2009-01-01 00:00:00.000 Dan Kramer
2 2008-01-01 00:00:00.000 Pam Slattery
3 2009-01-01 00:00:00.000 Sam Cohen

关于TSQL 选择最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3259386/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com