I would like to rank some data by date to obtain a sequential list (1, 2, 3) but ignore dates that are <3 days together.
For example:
11/10/2015 = 1
11/11/2015 = 2
11/12/2015 = NULL (within 3 days of previous date)
11/15/2015 = 3
What is an efficient way of doing this please? Thank you in advance.
I think you're going for something like this. Knowing the RDBMS would help.
with date_lags as
(
select
date,
lag(date) over(order by date) as last_date
from
table
)
select
date,
rank() over(order by date) as the_rank
from
date_lags
where
datediff(day, last_date, date) >= 3;
This is a bit challenging, because you don't have lag()
or cumulative sum. But, you can implement it using outer apply
(or a subquery):
select e.*,
(case when CountFlag = 1
then row_number() over (partition by CountFlag order by e.date)
end) as newcol
from example e outer apply
(select top 1 (case when e.date >= dateadd(day, 3, e2.date) then 1 else 0 end) as CountFlag
from example e2
where e2.date < e.date
order by e2.date desc
) eprev;
This uses a logic trick to get the NULL
value. Notice there is no WHERE
, so all values are assigned a rank. The outer query uses the same column for the case
condition and for the partition by
clause.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.