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, msbi skills, msbiskills.com, 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 SERVER Puzzles, SQL Skills, SQL Sudoku, SQLSERVER, T SQL Puzzles, T-SQL Challenge, The Bitwise AND Puzzle, Tough SQL Challenges, Tough SQL Puzzles, TSQL, TSQL Challenge, TSQL Challenges, TSQL Interview questions, TSQL Queries
T-SQL Query | [ The Multiple Join Single Query Puzzle ]
Puzzle Statement
- We have a table named Orders1 , dates and parts.
- You have join all these tables and return part information , date and count.
- Count is how many orders we have for this partid on this idate
- For details please check out the sample input and expected output
Sample Input
Parts
partid |
1 |
2 |
Dates
idate |
01-01-2008 |
02-01-2008 |
Orders1 Table
partid | idate |
1 | 01-01-2008 |
1 | 02-01-2008 |
2 | 01-01-2008 |
Expected Output
partid | idate | counts |
1 | 01-01-2008 | 1 |
1 | 02-01-2008 | 1 |
2 | 01-01-2008 | 1 |
2 | 02-01-2008 | 0 |
Rules/Restrictions
- Your solution should be should use “SELECT” statement or “CTE”
- Your solution should be generic in nature.
- No temp tables , No Ctes , No sub selects are allowed. Only Single Select required
- 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 Dates(idate datetime) insert into dates select '1/1/2008' insert into dates select '1/2/2008' create table parts(partid int) insert into parts select 1 insert into parts select 2 create table orders1(partid int,idate datetime) insert into orders1 select 1,'1/1/2008' insert into orders1 select 1,'1/2/2008' insert into orders1 select 2,'1/1/2008' — |
Update May 14 | Solution
-- /************ SOLUTION 1 | Deepak Sharma ****************/ SELECT p.partid,d.idate, COUNT(o.idate) Counts FROM parts p cross join dates d left join orders1 o ON d.idate = o.idate and p.partid = o.partid GROUP BY p.partid, d.idate ORDER BY 1 /************ SOLUTION 2 | Pawan Kumar Khowal ****************/ SELECT p.partid, d.idate,COUNT(o.partid) OVER (PARTITION BY o.partid , o.idate ORDER BY (SELECT NULL)) counts FROM orders1 o FULL OUTER JOIN Dates d CROSS JOIN parts p ON d.idate = o.idate AND p.partid = o.partid ORDER BY p.partid -- |
Add a comment if you have any other solution in mind. We all need to learn.
Keep Learning
Http://MSBISkills.com
Pawan Kumar Khowal
You must be logged in to post a comment.