Wednesday, August 20, 2014

Interview question - Select all the person from table PersonColor who have same color as ColorCode or have more colors than table ColorCode

http://blog.sqlauthority.com/2008/12/11/sql-server-interesting-interview-questions-part-2-puzzle-solution/

Question: Select all the person from table PersonColor who have same color as ColorCode or have more colors than table ColorCode.
UPDATE: Following solution is written with assumption that in SelectedColors table Name and ColorCode are Primary Key. This requirement was not specified in original question.
/*Answer to Interview Question*/SELECT Name
FROM PersonColors pc
INNER JOIN SelectedColors sc ON sc.ColorCode = pc.ColorCode
GROUP BY pc.Name
HAVING COUNT(pc.ColorCode) >= (SELECT COUNT(ColorCode) FROM SelectedColors)GO

If you want to download complete script for this interview question. Please download it from here.
Complete script of the puzzle is also listed here.
USE AdventureWorks
GO
/*Create First Table PersonColors*/CREATE TABLE PersonColors (Name VARCHAR(100), ColorCode VARCHAR(100))GO
INSERT INTO PersonColors (Name,ColorCode)VALUES ('Tom','Red'),('Tom','Blue'),('Tom','Green'),('Tom','Brown'),
(
'Mike','Red'),('Mike','Blue'),
(
'James','Green'),('James','Brown'),
(
'Joe','Red'),('Joe','Blue'),('Joe','Green'),
(
'Matt','Brown')GO
SELECT *FROM PersonColors
GO
/*Create Second Table SelectedColors*/CREATE TABLE SelectedColors (ColorCode VARCHAR(100))GO
INSERT INTO SelectedColors (ColorCode)VALUES ('Red'),('Blue'),('Green')SELECT *FROM SelectedColors
GO
/*Answer to Interview Question*/SELECT Name
FROM PersonColors pc
INNER JOIN SelectedColors sc ON sc.ColorCode = pc.ColorCode
GROUP BY pc.Name
HAVING COUNT(pc.ColorCode) >= (SELECT COUNT(ColorCode) FROM SelectedColors)GO
*Clean up DATABASE*/DROP TABLE PersonColors
DROP TABLE SelectedColors
GO

Let me know your opinion about this puzzle.

No comments:

Post a Comment