I need the last 3 dates for an order and these need to be returned in 1 row. I used an inline view to get the last 2 orders but do not know how to add a 2nd level of inline view to get the 3rd last order. Also, need to control for the fact that there may be only 1 or 2 order dates, or that there can be 2 orders on the same date. Here is what I did to get the last 2 dates.
select
cm.customerid,
max(cm.orderdate) as ordate2,
max(c1.ordate) as ordate1
from orders as cm
inner join
(select
customerid,
max(orderdate) as ordate,
count(*) as cnt1
from orders
group by customerid) as c1
on c1.customerid = cm.customerid
where cm.orderdate < c1.ordate or cnt1 = 1
group by cm.customerid
Can anyone help me on this?
Thank you.
select
cm.customerid,
max(cm.orderdate) as ordate2,
max(c1.ordate) as ordate1
from orders as cm
inner join
(select
customerid,
max(orderdate) as ordate,
count(*) as cnt1
from orders
group by customerid) as c1
on c1.customerid = cm.customerid
where cm.orderdate < c1.ordate or cnt1 = 1
group by cm.customerid
Can anyone help me on this?
Thank you.