Tags
Complex SQL Challenges, Complex TSQL Challenge, Interview Qs.SQL SERVER Questions, Interview Questions on SQL, InterviewQuestions, InterviewQuestions for SQL, Learn complex SQL, Learn SQL, Learn T-SQL, PL/SQL Challenges, Puzzles, Queries for SQL Interview, SQL, SQL 2012, SQL Challenge, SQL Challenges, SQL pl/sql puzzles, SQL Puzzles, SQL SERVER Interview questions, SQL SERVER2005/2008, 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 | [Movie Puzzle] – Write a query which will gets the movie details where Mr. Amitabh and Mr. Vinod acted together and their role is actor.
Sample Input
MName | AName | Roles |
A | Amitabh | Actor |
A | Vinod | Villain |
B | Amitabh | Actor |
B | Vinod | Actor |
D | Amitabh | Actor |
E | Vinod | Actor |
Expected Output
MName | AName | Roles |
B | Vinod | Actor |
B | Amitabh | Actor |
Rules/Restrictions
- The solution should be should use “SELECT” statement or “CTE”.
- Send your solution to pawankkmr@gmail.com
- Do not post you solution in comments section
Script
Use the below script to generate the source table and fill them up with the sample data.
–
-Create a sample movie table CREATE TABLE [Movie] ( [MName] [varchar] (10) NULL, [AName] [varchar] (10) NULL, [Roles] [varchar] (10) NULL ) GO --Insert data in the table INSERT INTO Movie(MName,AName,Roles) SELECT 'A','Amitabh','Actor' UNION ALL SELECT 'A','Vinod','Villan' UNION ALL SELECT 'B','Amitabh','Actor' UNION ALL SELECT 'B','Vinod','Actor' UNION ALL SELECT 'D','Amitabh','Actor' UNION ALL SELECT 'E','Vinod','Actor' --Check your data SELECT MName , AName , Roles FROM Movie |
SolutionS
— /* /* /* — |
Add a comment if you have any other solution in mind. We all need to learn.
Keep Learning
SELECT * FROM Movie WHERE MName IN (
SELECT distinct MName FROM Movie where AName = ‘Amitabh’ and Roles = ‘Actor’
INTERSECT
SELECT distinct MName FROM Movie where AName = ‘Vinod’ and Roles = ‘Actor’
)
LikeLiked by 1 person
SELECT MName , AName , Roles FROM Movie
WHERE MName IN (
SELECT MName FROM Movie
WHERE Roles = ‘Actor’
GROUP BY MName
HAVING COUnt(1)>1)
LikeLike
select * from #Movie a
where
exists (select * from #Movie b where a.MName=b.MName
and AName=’Amitabh’ and b.Roles=’Actor’)
and
exists (select * from #Movie b where a.MName=b.MName
and AName=’vinod’ and b.Roles=’Actor’)
LikeLike
select Mname from Movie where Mname in (
SELECT Mname FROM Movie as a where aname=’Vinod’ and
roles=’actor’) and roles=’actor’ and aname=’Amitabh’
LikeLike
SELECT a.*
FROM Movie a
JOIN Movie b ON a.MName=b.MName AND a.Roles=b.Roles AND a.AName!=b.AName;
LikeLiked by 1 person
with cte as (
SELECT
MName as MNameMatch
FROM Movie
where Roles = ‘Actor’
group by MName
having COUNT(case AName when ‘Amitabh’ then 1 when ‘Vinod’ then 1 else null end) = 2
)
select * from
Movie
inner join cte
on
cte.MNameMatch = Movie.MName
LikeLike