SQL 根据列值拉回最新的不同记录

SQL Pull Latest Distinct Records back based upon a column value

我的数据中大多数列都有唯一数据。我对 table 中只有三列感兴趣,其中两列具有唯一数据。

示例数据:

Ins_Cd | Encounter | Date
-------------------------------
A00    | 12345678  | 01-01-2001
A00    | 98765432  | 02-01-2001

从上面我要return第二条记录

Ins_Cd | Encounter | Date
-------------------------------
A00    | 98765432  | 02-01-2001

我写了下面的代码,我认为可以改进。它运行相当快 ~ 9 秒,视图中有将近 200 万条记录。

SELECT Pyr1_Co_Plan_Cd
, PtNo_Num
, Dsch_Date
, [rn] = ROW_NUMBER() over(
    partition by pyr1_co_plan_cd 
    order by dsch_date desc
    )

into #temp

FROM schema.my_view

where Med_Rec_No is not null
and Dsch_Date is not null
and LEFT(PtNo_Num, 1) != '2'
and LEFT(ptno_num, 4) != '1999'
and LEFT(ptno_num, 1) != '9'

order by Pyr1_Co_Plan_Cd
, Dsch_Date desc
;

select a.Pyr1_Co_Plan_Cd
, a.PtNo_Num
, a.Dsch_Date

from #temp as a

where a.rn = 1

order by a.Pyr1_Co_Plan_Cd
;

drop table #temp
;

以上确实给了我想要的。我怎样才能更有效地写这个?或者我应该在 codereview

上发布这个

这可能应该继续进行代码审查,但既然你在这里...

您的代码似乎包含不在您的数据中的列...特别是您的分区列。也许这是分区的正确列,但看起来很奇怪。

一种加快速度且不使用临时文件的方法 table。这将加快速度,因为不必执行 INSERT 操作。如果您查看 actual 执行计划,我敢打赌插入占总查询成本的很大一部分。相反,使用派生的 table 或 CTE。

select
       Pyr1_Co_Plan_Cd
     , PtNo_Num
     , Dsch_Date
from
    (SELECT 
       Pyr1_Co_Plan_Cd
     , PtNo_Num
     , Dsch_Date
     , [rn] = ROW_NUMBER() over(partition by pyr1_co_plan_cd order by dsch_date desc)
    FROM 
       schema.my_view
    where 
       Med_Rec_No is not null
       and Dsch_Date is not null
       and LEFT(PtNo_Num, 1) != '2'
       and LEFT(ptno_num, 4) != '1999'
       and LEFT(ptno_num, 1) != '9') x
where RN = 1
order by Pyr1_Co_Plan_Cd

如果您打算使用 TEMP TABLE,那么您还可以通过删除 SELECT INTO #temp 部分的 order by Pyr1_Co_Plan_Cd, Dsch_Date desc 来加快速度。这种排序是不必要的,对您没有任何好处,尤其是因为您在最终 select 中对结果进行排序,并使用 window 函数来计算具有 order by 的 RN .