I want to make customer segments based on their orders in different years (number of days before last order) using a SQL query. Below are the segments that I want:
- New Customer = Made an order for the very first time in whole data
- Repeat Customer L1 = Made an order at least once in last one year (365days)
- Repeat Customer L2 = Made an order at least once in last two years (but not in last one year)
- Repeat Customer L3 = Made an order at least once in last three years (but not in last two years)
- Unspecified = Any order that does not have any of the above conditions
This is the table that I have: (Small example, the data that I have is too huge)
| Date(yyyymmdd) | Customer_id |
|---|---|
| 20180403 | abc123 |
| 20180711 | def456 |
| 20180625 | mno789 |
| 20181123 | abc123 |
| 20190130 | ghi123 |
| 20190321 | def456 |
| 20190909 | ghi123 |
| 20191225 | jkl456 |
| 20200205 | abc123 |
| 20200617 | ghi123 |
| 20200817 | hij123 |
| 20210307 | mno789 |
| 20211009 | xyz345 |
This is the output I am trying to get through SQL (I am new to SQL):
| Year | Customer_id | Segment | Transactions |
|---|---|---|---|
| 2018 | abc123 | New Customer | 2 |
| 2018 | def456 | New Customer | 1 |
| 2018 | mno789 | New Customer | 1 |
| 2019 | ghi123 | New Customer | 2 |
| 2019 | def456 | Repeat Customer L1 | 1 |
| 2019 | jkl456 | New Customer | 1 |
| 2020 | abc123 | Repeat Customer L2 | 1 |
| 2020 | ghi123 | Repeat Customer L1 | 1 |
| 2020 | hij123 | New Customer | 1 |
| 2021 | mno789 | Repeat Customer L3 | 1 |
| 2021 | xyz345 | New Customer | 1 |
Your help would be really appreciated.
