Posts

Showing posts with the label partition by clause

TOP COMPETITORS: HACKERRANK

Problem Statement:  Julia just finished conducting a coding contest, and she needs your help assembling the leaderboard! Write a query to print the respective hacker_id and name of hackers who achieved full scores for more than one challenge. Order your output in descending order by the total number of challenges in which the hacker earned a full score. If more than one hacker received full scores in same number of challenges, then sort them by ascending hacker_id . Tables: 1. Hackers: The hacker_id is the id of the hacker, and name is the name of the hacker.   2. Difficulty: The difficult_level is the level of difficulty of the challenge, and score is the score of the challenge for the difficulty level. 3. Challenges: The challenge_id is the id of the challenge, the hacker_id is the id of the hacker who created the challenge, and difficulty_level is the level of difficulty of the challenge. 4. Submissions: The submission_id is the id of the su...

The Occupation: hackerrank problem

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. Table:   'OCCUPATIONS' table contain the column 'Name' and 'Occupation' Solution: select doc,prof,singer,act from ( select row_number() over(partition by Occupation order by Name) ron,Name as n,Occupation as o from OCCUPATIONS ) pro pivot (max(n)  for o in ('Doctor' as doc,'Actor' as act,'Professor' as prof,'Singer' as singer))  order by ron asc; Explanation: in the above query statement i am using row_number() function with the 'partition by' clause to append one column that contains row_number for each row in the subquery. in the subquery while assigning row_number() we...