SQL Server Group By with Max on Date字段

时间:2016-02-16 21:23:59

标签: sql sql-server

我希望我能解释我所拥有的问题,并希望能够指出我的方向。

我试图通过(电子邮件地址)对数据子集进行分组,然后我在日期字段上使用max(),但由于其他字段中的值不同,带回更多行然后需要。

我只想返回每个电子邮件地址的最大记录,并返回最大记录中同一行的字段。

不确定我怎么能写这个查询?

3 个答案:

答案 0 :(得分:1)

这是ROW_NUMBER的任务:

select *
from
 ( 
   select t.*,
      -- assign sequential number starting with 1 for the maximum date 
      row_number() over (partiton by email_address order by datecol desc) as rn
   from tab
 ) as dt
where rn = 1 -- only return the latest row

答案 1 :(得分:0)

您可以使用row_number()编写此查询:

select t.*
from (select t.*,
             row_number() over (partition by emailaddress order by date desc) as seqnum
      from t
     ) t
where seqnum = 1;

答案 2 :(得分:0)

这样的事情怎么样?

select a.*
from baseTable as a
inner join
(select Email,
       Max(EmailDate) as EmailDate
from baseTable
group by Email) as b
on a.Email = b.Email
and a.EmailDate = b.EmailDate