Tags

, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,


SQL Puzzle | The Multiple Sums Puzzle

This question was asked to me in one of the technical interviews I had recently attended. Here you have a column with values 1 to 7. Now you have to find sum of each digit with each remaming digits and get resuts where you have same sum multiple times.

Let me give you an example.

1+6 = 7
6+1 = 7
3+4 = 7
4+3 = 7
5+2 = 7
2+5 = 7

Now from the above example we need 3 rows only. e.g. 1+6 or 6+1 is same for an user.

Please check out the sample input values and sample expected output below.

Sample Input

ID
1
2
3
4
5
6
7

Expected Output

ID ID Sums
2 1 3
2 2 4
3 1 4
3 2 5
4 1 5
3 3 6
4 2 6
5 1 6
4 3 7
5 2 7
6 1 7
4 4 8
5 3 8
6 2 8
7 1 8
5 4 9
6 3 9
7 2 9
5 5 10
6 4 10
7 3 10
6 5 11
7 4 11
6 6 12
7 5 12
7 6 13

Rules/Restrictions

The solution should be should use “SELECT” statement or “CTE”.
Add your solution(s) in the comments section or send you solution(s) to pawankkmr@gmail.com

SOLUTION 1 | Using CrossJoin & Concat


--



IF OBJECT_ID('tempdb..#One') IS NOT NULL
    DROP TABLE #One

IF OBJECT_ID('tempdb..#Two') IS NOT NULL
    DROP TABLE #Two

SELECT s.ID a , x.ID b , s.ID + x.ID Sums INTO #One FROM SumPuzzle s
CROSS APPLY
(
	SELECT * FROM  SumPuzzle s1
)x 

SELECT Sums INTO #Two FROM #One
GROUP BY Sums
HAVING COUNT(*) > 1

SELECT LEFT(Rnk,1) ID , RIGHT(Rnk,1) ID , Sums
FROM
(
	SELECT DISTINCT b.Rnk, b.Sums FROM
	(
		SELECT c2.* , CASE WHEN a > b THEN CONCAT(a,b) ELSE CONCAT(b,a) END Rnk FROM #Two c1
		INNER JOIN #One c2 
		ON c1.Sums = c2.Sums		
	)b 
)v

IF OBJECT_ID('tempdb..#One') IS NOT NULL
    DROP TABLE #One

IF OBJECT_ID('tempdb..#One') IS NOT NULL
    DROP TABLE #Two



--

Add a comment if you have any other solution in mind. I would love to learn it. We all need to learn.

Enjoy !!! Keep Learning

Pawan Khowal 

Http://MSBISkills.com