如何获得不同的记录?

时间:2019-02-05 18:50:46

标签: sql sql-server database sql-order-by

我在数据库表中有以下记录。我想修改查询,以使带有Submitted_Date的唯一代表代码按降序排列。我怎么得到的?这就是我尝试过的

select distinct Rep_Code as repCode , Rep_Name as repName, Submitted_Date
FROM USBI_Interaction
where Rep_Code in 
  ('T203','A107') order by Submitted_Date desc 


T203    Amy N France    2/5/2019 6:52:15 AM
T203    Amy N France    2/5/2019 6:26:14 AM
T203    Amy N France    2/5/2019 6:23:27 AM
A107    Alan J Schmidt  2/5/2019 5:47:44 AM
T203    Amy N France    2/5/2019 1:24:35 AM

我应该得到如下结果(每个记录具有不同的代表代码。如果有多个记录具有相同的代表代码,则获取具有最新提交日期的记录)

T203    Amy N France    2/5/2019 6:52:15 AM
A107    Alan J Schmidt  2/5/2019 5:47:44 AM

3 个答案:

答案 0 :(得分:1)

聚合是您想要的吗?

select Rep_Code as repCode, Rep_Name as repName, MAX(Submitted_Date) as Submitted_Date
from USBI_Interaction
where Rep_Code in ('T203', 'A107') 
group by Rep_Code, Rep_Name
order by MAX(Submitted_Date) desc ;

答案 1 :(得分:0)

您需要row_number()

select top (1) with ties Rep_Code as repCode , Rep_Name as repName, Submitted_Date
from USBI_Interaction
where Rep_Code in ('T203','A107') 
order by row_number() over (partition by Rep_Code order by Submitted_Date desc);    

答案 2 :(得分:0)

使用row_number()窗口函数

    select repCode,repName,Submitted_Date
   from (
    select Rep_Code as repCode , Rep_Name as repName, Submitted_Date
    ,row_number() over(partition by Rep_Code ,Rep_Name 
                        order by Submitted_Date desc ) rn
           FROM USBI_Interaction
           where Rep_Code in ('T203','A107')
    ) t where t.rn=1 order by Submitted_Date desc