表
Email Status CreatedDate(mm/dd/yyyy)
abc@gmail.com Open 10/02/2018
abc@gmail.com Closed 10/06/2018
abc@gmail.com Prospect 10/04/2018
xyz@gmail.com closed 10/21/2018
xyz@gmail.com closed 10/01/2018
123@mail.com Open 10/04/2018
123@gmail.com Open 10/03/2018
123@gmail.com closed 10/02/2018
123@gmail.com closed 10/01/2018
输出
abc@gmail.com Prospect 10/04/2018
xyz@gmail.com closed 10/21/2018
123@gmail.com open 10/04/2018
以上输出基于以下条件:
答案 0 :(得分:2)
一种方法在子查询中使用row_number()
:
select t.*
from (select t.*,
row_number() over (partition by email
order by (case when status = 'prospect' then 1
when status = 'open' then 2
when status = 'closed' then 3
else 4
end), CreatedDate desc
) as seqnum
from t
) t
where seqnum = 1;
您也可以不使用子查询来表达这一点:
select top (1) t.*
from t
order by row_number() over (partition by email
order by (case when status = 'prospect' then 1
when status = 'open' then 2
when status = 'closed' then 3
else 4
end), CreatedDate desc
)