365 Days of Daily Coding: Day 9

I did 2 easy and 1 medium ranked Leetcode challenges since it’s weekend today. Let’s head straight towards the challenges.

Challenge 1:

Given the Cinema table with Id, Movie, Description and Rating as column headers, I had to find out movies that have odd numbers as their ID no. and description that does not contain the word ‘boring’.

idmoviedescriptionrating
1Wargreat 3D8.9
2Sciencefiction8.5
3irishboring6.2
4Ice songfantasy8.6
5House cardinteresting9.1
Sample of the table ‘cinema’

Expected Output:

idmoviedescriptionrating
5House cardinteresting9.1
1Wargreat 3D8.9
Sample of the output of Challenge 1

The query for the above challenge was as follows.

 SELECT * FROM cinema WHERE MOD(id,2) <> 0 
     AND LOWER(description) <> 'boring'
     ORDER BY rating DESC; 

The MOD() function returns the remainder after the division and therefore, any numbers that returns 0 when divided by 2 are even numbers. Another thing to highlight is that, it is always good to perform a search of a string first by converting the string to a lowercase.

Challenge 2:

Given two tables Person and Address, with (PersonID, FirstName and LastName) and (AddressId, PersonId, City and State) as column headers respectively, I had to query a report that provides the FirstName, LastName, City and State of each of the people.

Column NameType
PersonIdint
FirstNamevarchar
LastNamevarchar
Columns in the table ‘Person’
Column NameType
AddressIdint
PersonIdint
Cityvarchar
Statevarchar
Columns in the table ‘Address’

The query of the above challenge is as follows.

SELECT p.Firstname, p.Lastname, a.City, a.State 
 FROM Person p 
 LEFT JOIN Address a 
 ON p.PersonID = a.PersonID; 

The challenge was solved using simply a LEFT JOIN between the two tables ‘Person’ and ‘Address’.

Challenge 3:

Given a table called ‘Score’, I had to rank the scores. If there is a tie between two scores, both should have the same ranking. If there is a tie, the next ranking number should be consecutive integer value.

IDScores
13.5
23.65
34.00
43.85
54.00
63.65
Sample of the table ‘Score’

Expected Output:

ScoreRank
4.001
4.001
3.852
3.653
3.653
3.54
Sample of the output of Challenge 3

The solution to the above challenge was as follows.

SELECT Score, DENSE_RANK() AS Rank 
 FROM Scores
 ORDER BY Score DESC;

The function DENSE_RANK() was explained yesterday in my blog for Day 8. That’s it for today. I took a quite a chill pill today but I plan to solve more of the leetcode challenges tomorrow.

Leave a comment