根据状态和CreatedDate查询最新记录

时间:2018-10-18 10:10:42

标签: sql sql-server tsql

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

以上输出基于以下条件:

  1. 获取每封电子邮件的唯一记录。
  2. 条件1 假设“ abc@gmail.com”具有三个记录,并且如果 status =“ prospect”找到了与该记录无关的记录 createdDate和其他任何状态。
  3. 条件2 假设“ xyz@gmail.com”有两个记录,并且都属于 status =“ Closed”,然后检查CreatedDate并选择最新的  日期。
  4. 条件3 假设“ 123@gmail.com”有四个记录,其中两个处于打开状态,两个处于关闭状态,我们应采用打开状态并根据最新创建的记录进行选择日期。

1 个答案:

答案 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
                           )