[英]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.