I started studying SQL from a very famous site - HackerRank. Here I will try to provide multiple approaches & solutions to the same problem. It will help you learn and understand SQL in a better way.
Please make use of my blog posts for learning purpose only and feel free to ask your questions in the comment box below in case of any doubt.
Click Here for the previous blog-post in the series.
Recommended SQL Courses:
SQL Problem Statement:
Pivot the Occupation column in OCCUPATIONS so that each Name is sorted alphabetically and displayed underneath its corresponding Occupation. The output column headers should be Doctor, Professor, Singer, and Actor, respectively.
Note: Print NULL when there are no more names corresponding to an occupation.
Input Format:
The OCCUPATIONS table is described as follows:
OCCUPATIONS Columns |
Sample Input:
An OCCUPATIONS table that contains the following records:
Sample Output:
The first column is an alphabetically ordered list of Doctor names.
The second column is an alphabetically ordered list of Professor names.
The third column is an alphabetically ordered list of Singer names.
The fourth column is an alphabetically ordered list of Actor names.
The empty cell data for columns with less than the maximum number of names per occupation (in this case, the Professor and Actor columns) are filled with NULL values.
Solution: Using SET, CASE WHEN & ROW_NUM (MySQL Query):
NOTE:
- To understand the above solution, Try to print the inner SELECT query first.
- SET keyword is used to initiate variables like d, p, s & a with 0 value.
- ORDER BY NAME is used to get all the names first and then NULL.
- Here, MIN function in the outer SELECT query is used to select Name from the group of 1 Name & 3 NULL. you can use MAX instead of MIN here.
Eg. MIN(Jenny, NULL, NULL, NULL) will return Jenny.
Sample Output:
--------------------------------------------------------------------------------
Click here to see solutions for all Machine Learning Coursera Assignments.
&
Click here to see more codes for Raspberry Pi 3 and similar Family.
&
Click here to see more codes for NodeMCU ESP8266 and similar Family.
&
Click here to see more codes for Arduino Mega (ATMega 2560) and similar Family.
Feel free to ask doubts in the comment section. I will try my best to answer it.
If you find this helpful by any mean like, comment and share the post.
This is the simplest way to encourage me to keep doing such work.
Thanks & Regards,
-Akshay P Daga