如何删除 SQL 服务器中的非精确重复项
How to remove non exact duplicates in SQL Server
目前,我可以从每个报告中获取数据,并按案例类型过滤,然后再根据打开的案例和我想要的每个案例报告进行过滤。
然而,作为一个案例可以打开几个月,我只想要它出现的第一个月。例如,一个案例可以在 201904、201905 的每个报告中打开,然后在 201911 中重新打开,关于那个案例的很多信息都发生了变化,所以它不是完全重复的,但是我只是在 201904 报告中的案例数据之后。
目前我正在使用以下代码
Select ReportDate, CaseNo, Est, CaseType
From output.casedata
Where casetype='family' and Status='Open' AND (
Reportdate='201903' OR Reportdate='201904' OR Reportdate='201905'
or Reportdate='201906' or Reportdate='201907' or Reportdate='201908'
or Reportdate='201909' or Reportdate='201910' or Reportdate='201911'
or Reportdate='201912' or Reportdate='202001' or Reportdate='202002'
)
您可以使用 rank
window 函数找到每个案例编号的第一个日期的行,然后从中获取所有详细信息:
SELECT *
FROM (SELECT *, RANK() OVER (PARTITION BY CaseNo ORDER BY Reportdate) AS rk
FROM output.casedata
WHERE casetype = 'family' AND status='Open') t
WHERE rk = 1
如果我没听错,你想要每个案例最早的打开记录。
以下应该符合您的期望:
select c.*
from output.casedata c
where c.reportdate = (
select min(c1.reportdate)
where
c1.caseno = c.caseno
and c1.casetype = 'family'
and c1.status = 'open'
and c1.reportdate between '201903' and '202002'
)
为了性能,您需要 (caseno, casttype, status, reportdate)
上的索引。
请注意,我将 reportdate
上的过滤器简化为使用 between
而不是枚举所有可能的值。
目前,我可以从每个报告中获取数据,并按案例类型过滤,然后再根据打开的案例和我想要的每个案例报告进行过滤。
然而,作为一个案例可以打开几个月,我只想要它出现的第一个月。例如,一个案例可以在 201904、201905 的每个报告中打开,然后在 201911 中重新打开,关于那个案例的很多信息都发生了变化,所以它不是完全重复的,但是我只是在 201904 报告中的案例数据之后。
目前我正在使用以下代码
Select ReportDate, CaseNo, Est, CaseType
From output.casedata
Where casetype='family' and Status='Open' AND (
Reportdate='201903' OR Reportdate='201904' OR Reportdate='201905'
or Reportdate='201906' or Reportdate='201907' or Reportdate='201908'
or Reportdate='201909' or Reportdate='201910' or Reportdate='201911'
or Reportdate='201912' or Reportdate='202001' or Reportdate='202002'
)
您可以使用 rank
window 函数找到每个案例编号的第一个日期的行,然后从中获取所有详细信息:
SELECT *
FROM (SELECT *, RANK() OVER (PARTITION BY CaseNo ORDER BY Reportdate) AS rk
FROM output.casedata
WHERE casetype = 'family' AND status='Open') t
WHERE rk = 1
如果我没听错,你想要每个案例最早的打开记录。
以下应该符合您的期望:
select c.*
from output.casedata c
where c.reportdate = (
select min(c1.reportdate)
where
c1.caseno = c.caseno
and c1.casetype = 'family'
and c1.status = 'open'
and c1.reportdate between '201903' and '202002'
)
为了性能,您需要 (caseno, casttype, status, reportdate)
上的索引。
请注意,我将 reportdate
上的过滤器简化为使用 between
而不是枚举所有可能的值。