I'm trying to make a Teradata SQL query that will return the n-th chronological visit date for each user. E.g.,
user | visit_date
---------------------
a 1/1
b 1/10
c 1/20
a 1/3
a 1/4
b 1/5
c 1/15
b 1/9
> magic_query_for_Second_visit;
user | second
------------------
a 1/3
b 1/9
c 1/20
I tried something like the below, but Teradata shrieked that "Ordered analytical functions are not allowed in WHERE
clause." I've pulled my hair for a while but am not making much progress. Anyone seen this?
select user,
row_number() over (partition by user order by visit_date desc) as rnum
from visitstable
where rnum = 2
If I exclude the where
then my result looks promising... I just can't extract what I need!
user | visit_date | rnum
---------------------------
a 1/1 1
a 1/3 2
a 1/4 3
b 1/5 1
b 1/9 2
b 1/10 3
c 1/15 1
c 1/20 2
Thanks in advance for the help!