最近6个月使用t-sql在SQL Server中重复记录?

时间:2015-06-09 20:57:48

标签: sql-server tsql sql-server-2008-r2

我有一张桌子:

declare @t1 table(Pat_Ref int,regdt datetime)

insert into @t1 
values   (1,'2015-06-09 21:31:09.253')
        ,(1,'2015-04-09 21:31:09.253')
        ,(2,'2015-06-08 21:31:09.253')
        ,(2,'2015-03-09 21:31:09.253')
        ,(3,'2014-11-09 21:31:09.253')
        ,(3,'2015-02-15 21:31:09.253')
        ,(4,'2015-01-15 21:31:09.253')

我希望最近的regdt日期只有过去6个月的重复记录。

注意:首次重复记录可能超过6个月。

例如

(3, '2014-11-09 21:31:09.253') and 
(3,'2015-02-15 21:31:09.253')

这应被视为重复记录

结果应该是这样的:

Pat_Ref regdt
1       2015-06-09 21:31:09.253   
2       2015-06-08 21:31:09.253   
3       2015-02-15 21:31:09.253

我尝试了这个查询:

;with cte 
as (
    select * from (
        select *, ROW_NUMBER() over (partition by Pat_Ref order by regdt asc) Rn
        from @t1 where convert(date, regdt)>=DATEADD(MM, -6, convert(date,GETDATE()))
    ) t2 
        where t2.Rn>1)
        ,cte1 as ( select *,ROW_NUMBER() over (partition by Pat_Ref order by regdt desc) Rn1  from cte)
    select * from cte1
    where cte1.Rn1=1

我是这样的:

Pat_Ref  regdt         
1        2015-06-09 21:31:09.253    
2        2015-06-08 21:31:09.253    

任何帮助。感谢

2 个答案:

答案 0 :(得分:6)

使用having子句,其中count> 1和最大regdt>今天 - 6个月应该工作

SELECT  Pat_Ref, MAX(regdt)
FROM    @t1 t1
GROUP BY Pat_Ref
HAVING  COUNT(*) > 1 
        AND  MAX(regdt) >= DATEADD(MONTH, -6, GETDATE())

答案 1 :(得分:0)

看起来像一个群组中的存在子句会起作用:

SELECT Pat_Ref, MAX(regdt)
FROM @t1 t1
WHERE EXISTS (
    SELECT 1 
    FROM @t1 t 
    WHERE t.Pat_Ref = t1.Pat_Ref 
      and t.regdt <> t1.regdt 
      and t.regdt between DATEADD(MM, -6, t1.regdt) and DATEADD(MM, 6, t1.regdt)
)
GROUP BY Pat_Ref