Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL partition by on date range

Assume this is my table:

ID  NUMBER  DATE
------------------------
1   45      2018-01-01
2   45      2018-01-02
2   45      2018-01-27

I need to separate using partition by and row_number where the difference between one date and another is greater than 5 days. Something like this would be the result of the above example:

ROWNUMBER   ID  NUMBER  DATE
-----------------------------
1           1   45      2018-01-01
2           2   45      2018-01-02
1           3   45      2018-01-27

My actual query is something like this:

SELECT ROW_NUMBER() OVER(PARTITION BY NUMBER ODER BY ID DESC) AS ROWNUMBER, ...

But as you can notice, it doesn't work for the dates. How can I achieve that?

like image 680
Luis felipe De jesus Munoz Avatar asked Jul 30 '18 12:07

Luis felipe De jesus Munoz


People also ask

Can you partition by date in SQL?

You can partition on DateCreated column after you make it a clustered index.

What is partition by range in SQL?

A table that is partitioned by range is partitioned in such a way that each partition contains rows for which the partitioning expression value lies within a given range. Ranges should be contiguous but not overlapping, and are defined using the VALUES LESS THAN operator.

What is Maxvalue in range partitioning?

MAXVALUE represents an integer value that is always greater than the largest possible integer value (in mathematical language, it serves as a least upper bound). Now, any rows whose store_id column value is greater than or equal to 16 (the highest value defined) are stored in partition p3 .

How do you select a date range?

In the calendar, click the desired start date, then click the end date. The selected days are highlighted. OR. Enter start and end dates in the Date Range fields.


1 Answers

You can use lag function :

select *, row_number() over (partition by number, grp order by id) as [ROWNUMBER]
from (select *, (case when datediff(day, lag(date,1,date) over (partition by number order by id), date) <= 1 
                      then 1 else 2 
                 end) as grp
      from table
     ) t;
like image 111
Yogesh Sharma Avatar answered Sep 21 '22 22:09

Yogesh Sharma