以下内容适用于单个报告年度。您似乎想要获得一些东西:
- 停留时间超过 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 进行所有计算。