Listing 2: Complete Solution BEGIN CALLOUT A SET NOCOUNT ON; USE tempdb; DECLARE @top_pct AS NUMERIC(9, 8), @top_movie AS CHAR(1), @bottom_pct AS NUMERIC(9, 8), @bottom_movie AS CHAR(1), @iteration AS INT; DECLARE @CurrentVotes AS TABLE ( voter INT NOT NULL, rnk INT NULL, movie CHAR(1) NULL ); DECLARE @BottomVotes AS TABLE ( voter INT NOT NULL, rnk INT NOT NULL, movie CHAR(1) NOT NULL ); DECLARE @MovieTotals AS TABLE ( movie CHAR(1) NOT NULL, pct NUMERIC(9, 8) ); END CALLOUT A BEGIN CALLOUT B INSERT INTO @CurrentVotes(voter, rnk, movie) SELECT voter, rnk, movie FROM dbo.Votes WHERE rnk = 1; INSERT INTO @MovieTotals(movie, pct) SELECT movie, 1. * COUNT(*) / SUM(COUNT(*)) OVER() FROM @CurrentVotes GROUP BY movie; SELECT @top_pct = MAX(pct), @top_movie = RIGHT( MAX(CAST(pct AS CHAR(10)) + movie) , 1), @bottom_pct = MIN(pct), @bottom_movie = RIGHT( MIN(CAST(pct AS CHAR(10)) + movie) , 1) FROM @MovieTotals; SET @iteration = 1; END CALLOUT B BEGIN CALLOUT C WHILE @top_pct <= 0.5 AND @top_pct <> @bottom_pct BEGIN DELETE FROM @CurrentVotes OUTPUT deleted.voter, deleted.rnk, deleted.movie INTO @BottomVotes(voter, rnk, movie) WHERE movie IN (SELECT movie FROM @MovieTotals WHERE pct = @bottom_pct); INSERT INTO @CurrentVotes(voter, rnk, movie) SELECT TOP (1) WITH TIES V.voter, V.rnk, V.movie FROM dbo.Votes AS V JOIN @BottomVotes AS B ON V.voter = B.voter AND V.rnk > B.rnk WHERE V.movie IN (SELECT movie FROM @MovieTotals WHERE pct > @bottom_pct) ORDER BY ROW_NUMBER() OVER(PARTITION BY V.voter ORDER BY V.rnk); END CALLOUT C BEGIN CALLOUT D DELETE FROM @MovieTotals; INSERT INTO @MovieTotals(movie, pct) SELECT movie, 1. * COUNT(*) / SUM(COUNT(*)) OVER() FROM @CurrentVotes GROUP BY movie; SELECT @top_pct = MAX(pct), @top_movie = RIGHT( MAX(CAST(pct AS CHAR(10)) + movie) , 1), @bottom_pct = MIN(pct), @bottom_movie = RIGHT( MIN(CAST(pct AS CHAR(10)) + movie) , 1) FROM @MovieTotals; SET @iteration += 1; END END CALLOUT D BEGIN CALLOUT E IF @top_pct > 0.5 PRINT 'Winner is ' + @top_movie + ' with ' + CAST(CAST(100. * @top_pct AS NUMERIC(5, 2)) AS VARCHAR(6)) + ' percent after ' + CAST(@iteration AS VARCHAR(10)) + ' iterations.' ELSE IF @top_pct = @bottom_pct BEGIN PRINT 'Ties between the following movies after ' + CAST(@iteration AS VARCHAR(10)) + ' iterations:'; SELECT DISTINCT movie FROM @CurrentVotes; END ELSE PRINT 'Empty input or unknown error.' END CALLOUT E