concept SQL in category churn

appears as: SQL, SQL, The SQL, The SQL
Fighting Churn with Data

This is an excerpt from Manning's book Fighting Churn with Data.

The book is written from the point of view of a “data person”, meaning whoever is expected to take the raw data and come up with useful findings to help in the fight against churn. That person might have the title data scientist, data analyst, or machine learning engineer. Or they may be someone else who knows a bit about data and code and is being asked to fill those shoes. The book uses Python and SQL so it does assume that the data person is a coder. Although I advocate spreadsheets for presentation and sharing data (as I detail in the book) I do not recommend attempting the main analytic tasks of churn fighting in spreadsheets: There are many tasks that must be performed in sequence, and some of these are non trivial. And there is a need to “rinse and repeat” the process multiple times - that kind of workflow is well suited to short programs but difficult in spreadsheets and graphical tools.

Net retention is the only churn-related measurement that is more commonly quoted as a retention rate and not a churn rate. This is due in part to the scenarios that arise in multiprice subscriptions, particularly the possibility of negative net churn (net retention, on the other hand, is always positive). In the next section, you will learn how to calculate the Net Retention Rate with SQL, as well as more details about the use of PostgreSQL in this book.

Figure 3.4 Result of the event count SQL (listing 3.1) on the simulated social network dataset-like event. Your results will differ because the data was randomly simulated.
A screenshot of a cell phone Description automatically generated
Listing 3.13 INSERT SELECT SQL to calculate and save account tenure as a metric
WITH RECURSIVE date_vals AS (    #A
    SELECT i::timestamp AS metric_date    #B 
    FROM generate_series('2020-02-02', '2020-05-10', '7 day'::interval) i
),
earlier_starts AS    #C
(
    SELECT account_id, metric_date, 
        MIN(start_date) AS start_date    #D
    FROM subscription INNER JOIN date_vals
        ON start_date <= metric_date    #E
        AND (end_date > metric_date or end_date is null)
    GROUP BY account_id, metric_date
 
    UNION
 
    SELECT s.account_id, metric_date, s.start_date    #F
    FROM subscription s INNER JOIN earlier_starts e
        ON s.account_id=e.account_id
        AND s.start_date < e.start_date
        AND s.end_date >= (e.start_date-31)
)
INSERT INTO metric    G
(account_id,metric_time,metric_name_id,metric_value)
SELECT account_id, metric_date, 8 AS metric_name_id,   #H
    extract(days FROM metric_date-MIN(start_date)) 
        AS metric_value #I
FROM earlier_starts
GROUP BY account_id, metric_date
ORDER BY account_id, metric_date