Tags
Complex SQL Challenges, Complex TSQL Challenge, Interview Qs.SQL SERVER Questions, Interview questions on Joins, Interview Questions on SQL, InterviewQuestions, InterviewQuestions for SQL, Joins, Joins Interview questions, Joins Puzzle, Learn complex SQL, Learn SQL, Learn T-SQL, Objective Puzzle, PL/SQL Challenges, Puzzles, Queries for SQL Interview, SELECT Puzzle, SQL, SQL 2012, SQL 2014, SQL 2014 Interview Questions, SQL Challenge, SQL Challenges, SQL Joins, SQL pl/sql puzzles, SQL Puzzles, SQL Queries, SQL SERVER Interview questions, SQL Skills, SQL Sudoku, SQLSERVER, T SQL Puzzles, T-SQL Challenge, Tough SQL Challenges, Tough SQL Puzzles, TSQL, TSQL Challenge, TSQL Challenges, TSQL Interview questions, TSQL Queries
T-SQL Query | [ The Overlapping Dates Puzzle ]
Puzzle Statement
1. We have a table named Overlap.
2. Here we have start date and end date , now if the end date + 1 = start date; These dates are called Overlapping dates, we have to club those rows into one row
3. For details please check out the sample input and expected output
Sample Input
Id | StartDate | StopDate |
10 | 25-01-2014 | 30-01-2014 |
11 | 21-02-2014 | 24-02-2014 |
12 | 07-04-2014 | 30-04-2014 |
13 | 01-11-2014 | 30-11-2014 |
14 | 01-12-2014 | 31-12-2014 |
Expected Output
ID | StartDate | EndDate |
13 | 01-11-2014 | 01-12-2014 |
Rules/Restrictions
- Your solution should be should use “SELECT” statement or “CTE”
- Your solution should be generic in nature.
- Add your solution(s) in the comments section or send you solution(s) to pawankkmr@gmail.com
Script Use the below script to generate the source table and fill them up with the sample data.
-- CREATE TABLE Overlap ( Id INT ,StartDate DATETIME ,StopDate DATETIME ) GO INSERT INTO Overlap VALUES (10 ,'2014-01-25 00:00:00.000' ,'2014-01-30 00:00:00.000'), (11 ,'2014-02-21 00:00:00.000' ,'2014-02-24 00:00:00.000'), (12 ,'2014-04-07 00:00:00.000' ,'2014-04-30 00:00:00.000'), (13 ,'2014-11-01 00:00:00.000' ,'2014-11-30 00:00:00.000'), (14 ,'2014-12-01 00:00:00.000' ,'2014-12-31 00:00:00.000') -- |
Update 2 May | Solution 1
-- ------------------ SOLUTION 1 ---------------------- ;WITH CTE AS ( SELECT a.*,DATEADD(DAY, 1, A.StopDate) Ndt FROM Overlap a LEFT OUTER JOIN Overlap b ON a.Id = b.Id ) SELECT b.ID, b.StartDate , b.Ndt EndDate FROM CTE c LEFT JOIN CTE b ON c.StartDate = b.Ndt WHERE b.Id IS NOT NULL -- |
Add a comment if you have any other solution in mind. We all need to learn.
Keep Learning
Http://MSBISkills.com
You must be logged in to post a comment.