Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Repeat frequency of a tuple

ID              Date
7019730         16-03-2015
7019721         16-03-2015
7020250         16-03-2015
7219750         08-04-2015
7019730         22-03-2015
7019721         25-03-2015
7019730         28-03-2015
7019721         30-03-2015

For the table above, I want to extract how often are the IDs occurring with the difference between the dates as another column. I mean the output should be like:

ID              Date          Occurrence    Frequency
7019730         16-03-2015          1       0
7019721         16-03-2015          1       0
7020250         16-03-2015          1       0  
7219750         08-04-2015          1       0
7019730         22-03-2015          2       6
7019721         25-03-2015          2       9
7019730         29-03-2015          3       7
7019721         30-03-2015          3       5
like image 489
Max Avatar asked Feb 02 '26 03:02

Max


1 Answers

Here's one approach. Assuming your input table name is D:

declare @d1 table(x bigint, y bigint, id int, dt date);

insert @d1 (x, y, id, dt)
select 
    row_number() over (order by id, [date]) x, 
    (row_number() over (order by id, [date]) - 1) y, 
    id, 
    [date]
from 
    D
order by 
    id, [date];

select * 
from (
    select
        a.id, 
        a.dt, 
        row_number() over (partition by a.id order by a.id) as occurence, 
        coalesce(datediff(day, b.dt, a.dt), 0) as frequency
    from @d1 a
        left outer join @d1 b
        on a.y = b.x
        and a.id = b.id
    ) as results
order by occurence, id
like image 146
codekaizen Avatar answered Feb 04 '26 17:02

codekaizen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!