[英]DateDiff per Partition and row number
我有一个数据集-以下示例数据:
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
但是然后我假设我将需要为每个Reference
在每个RowNum
之间执行DATEDIFF
,这就是我RowNum
的问题。
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
尝试这个:
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.