我有一张桌子:

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')


我想要最近6个月内仅有重复记录的最新regdt日期。

注意:第一份重复记录可能会超过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


任何帮助。谢谢

最佳答案

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

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

关于sql-server - 最近6个月使用t-sql在SQL Server中重复记录了吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30742691/

10-13 07:40