I have the following table. Let's call it orders
. I would like to add a new column to this existing table which calculates the days apart from the first order date by the customerid. If there are 0 days apart from the minimum sold date, then it should be 0.
From this
customerid orderdate
1 1/21/2018
1 1/21/2018
1 2/21/2018
1 5/22/2018
2 3/22/2018
3 4/5/2018
3 4/5/2018
to this
customerid orderdate daysapart
1 1/21/2018 0
1 1/21/2018 0
1 2/21/2018 30
1 2/21/2018 123
2 3/22/2018 0
3 4/5/2018 0
3 4/5/2018 0
Using a Windowed Aggregate:
select customerid, orderdate,
orderdate - min(orderdate) over (partition by customerid) as daysapart
from mytab
Here is one approach, using a correlated subquery:
SELECT
t1.customerid,
t1.orderdate,
t1.orderdate - (SELECT MIN(t2.orderdate)
FROM your_table t2
WHERE t1.customerid = t2.customerid) daysapart
FROM your_table t1;
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.