合同开始和结束日期的客户流失率

时间:2019-05-02 00:52:40

标签: sql sql-server churn

我正在尝试计算客户的流失率,我所要玩的就是合同的开始和结束日期。

当日期年份为9999时,仅表示他们仍然是客户,我只考虑使用期限超过3个月(与在公司工作3个月或更长时间)的帐户。< / p>

CREATE TABLE #temp
(
 ACCOUNT varchar(20)NOT NULL
,CONTRACT_START_DATE DATETIME NOT NULL
,CONTRACT_END_DATE DATETIME NOT NULL
)
;


INSERT INTO #temp
VALUES('64074558792','20160729','20170805');
INSERT INTO #temp
VALUES('54654654664','20160810','20170110');
INSERT INTO #temp
VALUES('21454654764','20160112','20160812');
INSERT INTO #temp
VALUES('21654765134','20160101','20161231');
INSERT INTO #temp
VALUES('13214868794','20160811','99991231');
INSERT INTO #temp
VALUES ('88321546894','20160427','20160627');

SELECT *,
CASE WHEN CONTRACT_END_DATE <> '99991231' THEN DATEDIFF(DAY, CONTRACT_START_DATE,CONTRACT_END_DATE) ELSE null END AS TENURE
FROM #temp

1 个答案:

答案 0 :(得分:0)

以下内容适用于单个报告年度。似乎有些事情您正在尝试获得:

-停留时间超过x个月的客户数量

-%停留时间超过x个月的客户

年内

-%的客户流失

DECLARE @records TABLE
(
 ACCOUNT varchar(20)NOT NULL
,CONTRACT_START_DATE DATETIME NOT NULL
,CONTRACT_END_DATE DATETIME NOT NULL
);

DECLARE @ReportingYear INT = 2016;
DECLARE @MinTenureMonths INT = 3;


INSERT INTO @records
VALUES('64074558792','20160729','20170805'),
('54654654664','20160810','20170110'),
('21454654764','20160112','20160812'),
('21654765134','20151011','20161231'),--I changed this one
('13214868794','20160811','99991231'),
('88321546894','20160427','20160627');

SELECT *,
[CustomerGained]    = IIF(YEAR(CONTRACT_START_DATE) = @ReportingYear,1,0),
[CustomerLost]      = IIF(YEAR(CONTRACT_END_DATE) = @ReportingYear,1,0) ,
[ExistingCustomer]  = IIF(CONTRACT_START_DATE < DATEFROMPARTS(@ReportingYear,1,1)
                        AND CONTRACT_END_DATE > DATEFROMPARTS(@ReportingYear,12,31), 1, 0),
[CurrentCustomer]   = IIF(CONTRACT_END_DATE = '99991231 00:00:00.000',1,0),
[MinTenureExceeded] = IIF(DATEDIFF(MONTH, CONTRACT_START_DATE, CONTRACT_END_DATE) >= @MinTenureMonths,1,0)
FROM @records;

With recordCTE AS
(
SELECT 
    [CustomersGained]   = SUM(IIF(YEAR(CONTRACT_START_DATE) = @ReportingYear,1,0)),
    [CustomersLost]     = SUM(IIF(YEAR(CONTRACT_END_DATE) = @ReportingYear,1,0)),
    [MinTenureExceeded] = SUM(IIF(DATEDIFF(MONTH, CONTRACT_START_DATE, CONTRACT_END_DATE) >= @MinTenureMonths,1,0)),
    [ExistingCustomers] = SUM(IIF(CONTRACT_START_DATE < DATEFROMPARTS(@ReportingYear,1,1)
                            AND CONTRACT_END_DATE > DATEFROMPARTS(@ReportingYear,12,31), 1, 0)),
    [CurrentCustomer]   = SUM(IIF(CONTRACT_END_DATE = '99991231 00:00:00.000',1,0)),
    [TotalCustomers]    = COUNT(1)
FROM @records
)

SELECT  c.CustomersGained,
        c.CustomersLost,
        c.MinTenureExceeded,
        c.ExistingCustomers,
        [% Lost] = CAST(((c.CustomersLost * 1.0) / c.TotalCustomers) * 100 AS DECIMAL(14,2)),
        [% Gained] = CAST(((c.CustomersGained * 1.0) / c.TotalCustomers) * 100 AS DECIMAL(14,2))
FROM recordCTE c;

您需要确定是只查找单个报告年度,报告期间还是总计。如果需要所有内容,只需使用CurrentCustomers进行所有计算即可。