TSQL Challenge 20 - Solution By Michael Lewis



--Michael_Lewis_tsqlchallenge_20.sql
with fib as (
	select convert(bigint, 1) as fibnum, convert(bigint, 0) as prev, 1 as iter, 0 as reps
	union all
	select convert(bigint, 1), convert(bigint, 1), 2, 0
	union all
	select fibnum + prev, fibnum, iter + 1,
		case when convert(varchar(20),fibnum + prev) like '%00%' then 1 else 0 end +
		case when convert(varchar(20),fibnum + prev) like '%11%' then 1 else 0 end +
		case when convert(varchar(20),fibnum + prev) like '%22%' then 1 else 0 end +
		case when convert(varchar(20),fibnum + prev) like '%33%' then 1 else 0 end +
		case when convert(varchar(20),fibnum + prev) like '%44%' then 1 else 0 end +
		case when convert(varchar(20),fibnum + prev) like '%55%' then 1 else 0 end +
		case when convert(varchar(20),fibnum + prev) like '%66%' then 1 else 0 end +
		case when convert(varchar(20),fibnum + prev) like '%77%' then 1 else 0 end +
		case when convert(varchar(20),fibnum + prev) like '%88%' then 1 else 0 end +
		case when convert(varchar(20),fibnum + prev) like '%99%' then 1 else 0 end
	from fib
	where iter between 2 and 91
)
select reps as NumRepeats, fibnum as FiboNumber
from (
select reps, fibnum, row_number() over(partition by reps order by reps, fibnum) as seqno
from fib
where reps > 0) as a
where seqno <= 5
order by reps, fibnum

Did you find something incorrect/wrong with this solution? Take a few seconds to Report It.

Did you understand how this solution work? If you find it difficult to understand, you can Request an Explanation or you can Write an explanation to help others better understand this solution.