The description you wrote: "not same for two consicutive years" conflicts with your sample of:"is same for YearMonth='201005' and YearMonth='201006'"So I'm not sure if you want to base this on the YearMonth or just Year. But here is an example for YearMonth:declare @t table (CustomerCode int, YearMonth int, Description varchar(50), Points int)insert @tselect 00000241, 201005, '2. Dispenser Share (?????)' ,1400 union allselect 00000241, 201005, '4. Lighting / No Blockage (????? / ?????)' ,1000 union allselect 00000241, 201006, '2. Dispenser Share (?????)' ,1400 union allselect 00000241, 201006, '4. Lighting / No Blockage (????? / ?????)' ,1000 union allselect 00002139, 201005, '2. Dispenser Share (?????)' ,600 union allselect 00002139, 201005, '4. Lighting / No Blockage (????? / ?????)' ,300 union allselect 00002139, 201006, '1. PM Exclusives (PM ??)' ,1100 union allselect 00002139, 201006, '2. Dispenser Share (?????)' ,500 union allselect 00002139, 201006, '3. Planogram (??????)' ,300 union allselect 00002139, 201006, '4. Lighting / No Blockage (????? / ?????)' ,300 union allselect 00004414, 201005, '1. PM Exclusives (PM ??)' ,1500 union allselect 00004414, 201005, '2. Dispenser Share (?????)' ,600 union allselect 00004414, 201005, '3. Planogram (??????)' ,450 union allselect 00004414, 201005, '4. Lighting / No Blockage (????? / ?????)' ,450 union allselect 00004414, 201006, '1. PM Exclusives (PM ??)' ,2400 union allselect 00004414, 201006, '2. Dispenser Share (?????)' ,900 union allselect 00004414, 201006, '3. Planogram (??????)' ,600 union allselect 00004414, 201006, '4. Lighting / No Blockage (????? / ?????)' ,600;with cte as ( select customerCode ,YearMonth ,sum(Points) sumPoints ,row_number() over (order by customercode, yearMonth) as rownum from @t group by customerCode, YearMonth)select c.*from cte aleft outer join cte b on b.rownum-1 = a.rownuminner join @t c on c.customerCode = a.customerCode and c.YearMonth = a.YearMonthwhere a.sumPoints != isNull(b.sumPoints,-1)OUTPUT:(18 row(s) affected)CustomerCode YearMonth Description Points------------ ----------- -------------------------------------------------- -----------241 201006 2. Dispenser Share (?????) 1400241 201006 4. Lighting / No Blockage (????? / ?????) 10002139 201005 2. Dispenser Share (?????) 6002139 201005 4. Lighting / No Blockage (????? / ?????) 3002139 201006 1. PM Exclusives (PM ??) 11002139 201006 2. Dispenser Share (?????) 5002139 201006 3. Planogram (??????) 3002139 201006 4. Lighting / No Blockage (????? / ?????) 3004414 201005 1. PM Exclusives (PM ??) 15004414 201005 2. Dispenser Share (?????) 6004414 201005 3. Planogram (??????) 4504414 201005 4. Lighting / No Blockage (????? / ?????) 4504414 201006 1. PM Exclusives (PM ??) 24004414 201006 2. Dispenser Share (?????) 9004414 201006 3. Planogram (??????) 6004414 201006 4. Lighting / No Blockage (????? / ?????) 600(16 row(s) affected)
Be One with the OptimizerTG