您对不活动期的定义有点模糊,例如您是否考虑雇用/解雇日期?以下代码实现了一种不需要递归的解释。
-- Sample data.
declare @Sales as Table (
SalesPerson VarChar(10), SalesYear Int, SalesMonth Int, TotalSales Int );
insert into @Sales ( SalesPerson, SalesYear, SalesMonth, TotalSales ) values
( 'Dave', 2011, 1, 27) ,
( 'Meg', 2012, 7, 162 ),
( 'Randy', 2011, 3, 0 ),
( 'Julio', 2013, 8, 15 ),
( 'Bob', 2014, 12, 0 ),
( 'Mary', 2012, 5, 20 ),
( 'William', 2014, 1, 30 ),
( 'William', 2014, 2, 0 ),
( 'William', 2014, 4, 10 ),
( 'William', 2014, 6, 3 ),
( 'William', 2014, 7, 90 ),
( 'William', 2014, 12, 5 );
select * from @Sales;
-- Analyze it.
with
-- Get only the nonzero sales rows and combine the year/month into a single integer.
NonZeroSales as (
select SalesPerson, SalesYear * 12 + SalesMonth as CombinedMonth, TotalSales
from @Sales
where TotalSales <> 0 ),
-- Add row numbers for each sales person.
NonZeroSalesWithRN as (
select SalesPerson, CombinedMonth, TotalSales,
Row_Number() over ( partition by SalesPerson order by CombinedMonth ) as RN
from NonZeroSales )
-- Match adjacent rows for each sales person.
-- If there is a gap of three or more months then indicate it in a status column.
select L.SalesPerson,
Floor( L.CombinedMonth / 12 ) as SalesYear, L.CombinedMonth % 12 as SalesMonth,
L.TotalSales,
case when R.CombinedMonth - L.CombinedMonth > 3 then 'Gap > 3 Months' else 'Okay' end as SalesStatus
from NonZeroSalesWithRN as L inner join
NonZeroSalesWithRN as R on R.SalesPerson = L.SalesPerson and R.RN = L.RN + 1;
-- Tip: To see what is going on, or debug, multiple CTEs replace the last select with
-- select * from NonZeroSales
-- select * from NonZeroSalesWithRN