Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
Author |
Topic |
masterdineen
Aged Yak Warrior
550 Posts |
Posted - 2014-11-27 : 11:29:55
|
Hello everyone, Not been on here for a while. Been able to sort myself out with quite a few bits. Hope your all doing well.I have the below dataset as an example.customerReferenceNumber RaceDay Game_Year Retention10004952 Day 3 2007 New10004952 Day 3 2008 Retained10004952 Day 3 2010 Returned10004952 Day 3 2011 Retained10004952 Day 5 2007 New10004952 Day 5 2008 Retained10004952 Day 5 2010 Returned10004952 Day 5 2011 RetainedThe Retention column is what I am trying to work out with sql. The problem I am having is working out how to look for missing years where you would see a Retention value of Returned. In the above example. I am trying to achieve the Returned value, as you can see, the year 2009 is missing. Otherwise 2009 would be Retained. could someone help me out please.RegardsRob |
|
viggneshwar
Yak Posting Veteran
86 Posts |
Posted - 2014-12-04 : 10:34:36
|
declare @tbl as table( customerReferenceNumber varchar(20), RaceDay varchar(10), Game_Year int, Retentions varchar(10))insert into @tblselect 10004952, 'Day 3', 2007, 'New' unionselect 10004952, 'Day 3', 2008, 'Retained' unionselect 10004952, 'Day 3', 2010, 'Returned' unionselect 10004952, 'Day 3', 2011, 'Retained' unionselect 10004952, 'Day 5', 2007, 'New' unionselect 10004952, 'Day 5', 2008, 'Retained' unionselect 10004952, 'Day 5', 2010, 'Returned' unionselect 10004952, 'Day 5', 2011, 'Retained' ;with maxtblas ( select MAX(game_Year) as maxgameyear, customerReferenceNumber, RaceDay from @tbl group by customerReferenceNumber, RaceDay ),maxtbl1as ( select top 1 game_Year, customerReferenceNumber, RaceDay from @tbl order by customerReferenceNumber, RaceDay, game_Year union all select a.Game_Year+1, a.customerReferenceNumber, a.RaceDay from maxtbl1 a inner join maxtbl b on a.customerReferenceNumber = b.customerReferenceNumber and a.RaceDay = b.RaceDay where a.Game_Year <= b.maxgameyear ) select a.*from maxtbl1 aleft outer join @tbl bon a.customerReferenceNumber = b.customerReferenceNumberand a.RaceDay = b.RaceDay and a.Game_Year = b.Game_Year where b.Game_Year is nullRegardsViggneshwar A |
|
|
|
|
|
|
|