2

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

当日期年份为 9999 时,仅表示他们仍然是客户,我只想考虑任期超过 3 个月的帐户(如在公司工作 3 个月或更长时间)。

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
4

1 回答 1

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 进行所有计算。

于 2019-05-02T06:57:20.410 回答