每个分区的DateDiff和行号

时间:2014-12-18 00:15:13

标签: sql sql-server tsql sql-server-2012

我有一个数据集 - 下面的示例数据:

Username         | CreatedDate     |  Reference  |  Note
BOB                2014-05-23         Ref1          blah
BOB                2014-09-23         Ref1          blah
BOB                2014-05-24         Ref2          blah 
BOB                2014-06-23         Ref3          blah
BOB                2014-08-23         Ref3          blah
BOB                2014-01-01         Ref8          blah
BOB                2014-08-18         Ref8          blah
ERIC               2014-12-23         Ref13         blah
ERIC               2014-01-01         Ref18         blah
ERIC               2014-03-18         Ref18         blah

数据将包含多个用户。

我有一个要求,我需要突出显示任何用户和参考,这些用户和参考文件比每3个月更频繁地创建一个笔记。

所以我的结果是:

Username     |  Reference  |  
BOB             Ref3          
ERIC            Ref18         

有人可以就如何解决这个问题提出建议吗?

我添加了一个:

ROW_NUMBER () OVER (PARTITION BY Usernanme, Reference, ORDER BY CreatedDate) as RowNum

但是我假设我需要在每个DATEDIFF RowNum之间Reference和我被卡住的地方之间{{1}}。

2 个答案:

答案 0 :(得分:2)

SQL小提琴:http://sqlfiddle.com/#!6/d41d8/23459

declare @data table (
      Id int not null identity(1,1)
    , Username nvarchar(16)
    , CreatedDate date
    , Reference nvarchar(16)
    , Note nvarchar(16)
)

insert @data
      select 'BOB',                '2014-05-23',         'Ref1',          'blah'
union select 'BOB',                '2014-09-23',         'Ref1',          'blah'
union select 'BOB',                '2014-05-24',         'Ref2',          'blah'
union select 'BOB',                '2014-06-23',         'Ref3',          'blah'
union select 'BOB',                '2014-08-23',         'Ref3',          'blah'
union select 'BOB',                '2014-01-01',         'Ref8',          'blah'
union select 'BOB',                '2014-08-18',         'Ref8',          'blah'
union select 'ERIC',               '2014-12-23',         'Ref13',         'blah'
union select 'ERIC',               '2014-01-01',         'Ref18',         'blah'
union select 'ERIC',               '2014-03-18',         'Ref18',         'blah'

select Username, Reference
from @data a
where exists (
    select top 1 1 
    from @data b 
    where b.Username = a.Username 
    and b.Reference = a.Reference 
    and b.CreatedDate between dateadd(month,-3,a.CreatedDate) and dateadd(month,3,a.CreatedDate)
    and b.Id <> a.id --exclude the record itself (if you don't have an id column instead check for more than 1 match)
)
group by Username, Reference

答案 1 :(得分:1)

试试这个:

SELECT DISTINCT Username, Reference
FROM (SELECT Username, CreatedDate, Reference
, LAG(CreatedDate) OVER (PARTITION BY Username, Reference ORDER BY CreatedDate) as LastDate
FROM theTable) sub
WHERE DATEDIFF(month, sub.LastDate, sub.CreatedDate) < 3 and sub.LastDate is not null;