从同一个表中只获取最大创建日期

时间:2014-05-12 01:30:03

标签: sql sql-server date get max

我想从表中获取数据,但只选择最新或最大CreateDate

这是我的疑问:

select Username, Password,Status,FirstLogin,CreateDate,UpdateDate,MasterID,FullName,Address,tm.Email,TempEmail,VerificationCode,PhoneNo,TempPhonoNo,TempPassword,LastSignIn,TempAccount,bod,ktp,Gender,CustType,VIP from UserData t 
    inner join (
        select Email, max(CreateDate) as MaxDate
        from userdata
        group by Email
    ) tm on t.Email = tm.Email and t.CreateDate = tm.MaxDate 

但不幸的是,我只是为同一封电子邮件获得了多个结果,我只想获得一封具有最大创建日期的电子邮件:

这里的创建日期完全相同:

CreateDate                          FullName        Email   
2012-08-14 16:37:16.900     Mrs a       yyyyy@yyy.com   
2012-08-14 16:37:16.900     mrs a       yyyy@yyyy.com   

以及不同的创建日期:

2012-11-24 20:34:44.930 0   zzzzz       zzzzz@zzz.com
2012-11-16 08:13:45.217 0   zzzz    zzzz@zzzz.com

但我只想得到这样的结果:

 CreateDate                         FullName        Email   
    2012-08-14 16:37:16.900     Mrs a       yyyyy@yyy.com
2012-11-24 20:34:44.930 0   zzzzz       zzzzz@zzz.com

2 个答案:

答案 0 :(得分:1)

如果您没有足够的唯一性来使用GROUP BY或DISTINCT,则可以使用ROW_NUMBER。它不是最快的功能,但它会给你带来独特性。 e.g。

SELECT
     I.CreateDate
    ,I.FullName
    ,I.Email
FROM (
    SELECT
         T.CreateDate
        ,T.FullName
        ,T.Email
        ,ROW_NUMBER() OVER (
                            PARTITION BY T.Email 
                            ORDER BY T.FullName
                           ) SEQ
    FROM UserData t
        INNER JOIN (
                    SELECT 
                        Email
                        ,MAX(CreateDate) AS MaxDate
                    FROM userdata
                    GROUP BY Email
                    ) TM
            ON T.Email = TM.Email
                AND T.CreateDate = TM.MaxDate
    ) I
WHERE I.SEQ = 1

答案 1 :(得分:1)

我认为这是一种非常简单的方式来获得你想要的东西:

select Username, Password, Status, FirstLogin, CreateDate, UpdateDate, MasterID, FullName,  
       Address, Email, TempEmail, VerificationCode, PhoneNo, TempPhonoNo, TempPassword,    
       LastSignIn, TempAccount, bod, ktp, Gender, CustType, VIP
from (select ud.*, row_number() over (partition by email order by CreateDate desc) as seqnum
      from UserData ud
     ) ud
where seqnum = 1;

您只需要使用窗口函数row_number(),而不需要其他连接或聚合。