SQL Puzzle | The INNER JOIN – Two Rows PUZZLE | SQL Interview Question

This is something really interesting. Here you have to join these two tables and provide the resultated data but the matching rows into Multiple Rows. Please check out the sample input and the expected output.

Sample Input

Table 1 –

Id Vals
1 Pawan
2 Sharlee
3 Harry

Table 2 –

Id Vals
1 Kumar
2 Diwan

Expected Output

Id Vals
1 Pawan
1 Kumar
2 Sharlee
2 Diwan

Script – DDL and INSERT Sample Data

 -- CREATE TABLE T1N1 ( Id INT ,Vals Varchar(10) ) GO INSERT INTO T1N1 VALUES (1,'Pawan'), (2,'Sharlee'), (3,'Harry') GO CREATE TABLE T1N2 ( Id INT ,Vals Varchar(10) ) GO INSERT INTO T1N2 VALUES (1,'Kumar'), (2,'Diwan') GO SELECT * FROM T1N1 GO SELECT * FROM T1N2 GO --

SOLUTION 1

 -- SELECT Id,Vals FROM ( SELECT a.* , 1 Ord FROM T1N1 a INNER JOIN T1N2 b ON a.Id = b.Id UNION ALL SELECT b.* , 2 Ord FROM T1N1 a INNER JOIN T1N2 b ON a.Id = b.Id )x ORDER BY Id, Ord GO --

OUTPUT – 1

 -- Id Vals ----------- ---------- 1 Pawan 1 Kumar 2 Sharlee 2 Diwan (4 rows affected) --

SOLUTION 2

 -- SELECT Id,Vals FROM ( SELECT a.* , 1 Ord FROM T1N1 a CROSS APPLY ( SELECT NULL v FROM T1N2 b WHERE a.Id = b.Id )x UNION ALL SELECT x.* , 2 Ord FROM T1N1 a CROSS APPLY ( SELECT * FROM T1N2 b WHERE a.Id = b.Id )x )x ORDER BY Id, Ord GO --

OUTPUT – 2

 -- Id Vals ----------- ---------- 1 Pawan 1 Kumar 2 Sharlee 2 Diwan (4 rows affected) --

Enjoy 🙂

Pawan Khowal

Pawan is a SQL Server Developer. If you need any help in writing code/puzzle or training please email at – pawankkmr”AT”gmail.com. Meanwhile please go throgh the top pages from his blog.

Page Detail URL
☛ SQL Tricky Queries https://msbiskills.com/sql-puzzles-finding-outputs/
☛ SQL Server Performance tuning Articles https://msbiskills.com/sql-performance-tuning/
☛ SQL Server Articles https://msbiskills.com/t-sql/
☛ SQL Interview Questions & Answers https://msbiskills.com/sql-server-interview-questions/