We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Notice from the image, under professor column, the first Name is indexed as 1, the next name "Birtney" as 2. That is what I mean by index w.r.t occupation.
The below code will only give the "RowNumber" column, to get the result like in image proceed to step 3.
temp - Since I created a temporary table inside the query, I have to give it an alise. It is a good practise.
Why MIN in the select statement?
Since some of us here may not be fimilar with sql, I'll start with where I left so you get the whole picture.
Once you complete step 3, add "ORDER BY Name" (Refer above code on where to add Order by clause). The result will look like this https://imgur.com/aBHUqN6
What changed? the names in all four columns are sorted as per alphabetical order.
Now, we only want the names and not the NULL values from our virtual table. How can we do that? - There maybe be multiple ways, lets us consider the MIN/MAX (Yes, you can replace MIN with MAX and you will get the same result)
Without GROUP BY clause - When a MIN/MAX is used in a Select statement, it will return The "LOWEST" element from each column (which happened to be the first element because we used ORDER BY, if you use MAX, you will get the last element from each column). It will look like this https://imgur.com/XDZzc4Z
That means, you will always get a single row from a table.
When you use MIN/MAX in select statement, it will return a single row from the table with the LOWEST/HIGHEST value element from EACH column.
With GROUP BY clause, it will return the LOWEST/HIGHEST value element from each column and EACH group. Refer to the image attached on my main thread and connect this comment. You will get it.
This has got to be the best explained comment in all of hacker rank i have seen yet. Kudos to you for going the extra mile to explain to us mere mortals.
SELECT MAX(DOCTORS), MAX(PROFESSORS), MAX(SINGERS), MAX(ACTORS)
FROM
( SELECT
ROW_NUMBER() OVER (PARTITION BY OCCUPATION ORDER BY NAME) AS ROWNUMBER,
CASE WHEN OCCUPATION = "DOCTOR" THEN NAME END AS "DOCTORS",
CASE WHEN OCCUPATION = "PROFESSOR" THEN NAME END AS "PROFESSORS",
CASE WHEN OCCUPATION = "SINGER" THEN NAME END AS "SINGERS",
CASE WHEN OCCUPATION = "ACTOR" THEN NAME END AS "ACTORS"
FROM OCCUPATIONS ) AS SRC
GROUP BY SRC.ROWNUMBER
ORDER BY SRC.ROWNUMBER;
Thank you so much, it is so clear and really explains a lot.
While I have a small doubt about the order by clause.
Could anyone explain why the RowNumber that is set in the 'case when' statement will be sorted again? I thought that the ORDER BY clause is operated after the SELECT statement, so should not the RowNumber be set with the rows that name was not sorted yet?
Exemplifying from
raiyanger24's picture example that - Julia will still be in RowNumber of 1 for Doctor.even after an order by execution
Thank you so much guys!
The spam blocker is getting me because I'm trying to copy and paste the code I used to investigate. I can still share the conclusion though:
Contrary to what one is taught, it seems not everything in SELECT is executed before ORDER BY. It seems that anytime you derive a column (using CASE, by doing arithmetic, etc.), that column is going to be formed off of the ordered version of the non-derived fields if the field for the ORDER BY clause is non-derived.
If we run the inner subquery, then it would return following result set
Since we want all the peoples for specific row_number() to appear in the same row, we are using group by. And, when using group by, we can either select the columns in the group by list, or use aggregate function. So, in my case I used MIN, but in this case doing, MAX would have given the same result.
Thanks a lot, every beautiful and clear explanation. Do you have any youtube channel or blog about SQL or coding or data stuff,.. I wanna subcribe yours:))
Adding my voice to the chorus of thanks for this - thank you!
It would have taken me a very long time to figure that out alone - I've really learned something from this exercise and your explanation.
Occupations
You are viewing a single comment's thread. Return to all comments →
Let me break it down in steps (answer in MySQL)
Step 1:
Create a virtual table in your head of the data given to us. It look like this https://imgur.com/u6DEcNQ
Step 2:
Create an index column with respect to occupation as "RowNumber".https://imgur.com/QzVCWFn
Notice from the image, under professor column, the first Name is indexed as 1, the next name "Birtney" as 2. That is what I mean by index w.r.t occupation.
The below code will only give the "RowNumber" column, to get the result like in image proceed to step 3.
Step 3:
Combine the result from step 1 and step 2:
Step 4:
Now, Order_by name then Group_By RowNumber.
Using Min/Max, if there is a name, it will return it, if not, return NULL.
**EDIT** I can see many asking why MIN or temp?
temp - Since I created a temporary table inside the query, I have to give it an alise. It is a good practise.
Why MIN in the select statement? Since some of us here may not be fimilar with sql, I'll start with where I left so you get the whole picture.
What changed? the names in all four columns are sorted as per alphabetical order.
Now, we only want the names and not the NULL values from our virtual table. How can we do that? - There maybe be multiple ways, lets us consider the MIN/MAX (Yes, you can replace MIN with MAX and you will get the same result)
Without GROUP BY clause - When a MIN/MAX is used in a Select statement, it will return The "LOWEST" element from each column (which happened to be the first element because we used ORDER BY, if you use MAX, you will get the last element from each column). It will look like this https://imgur.com/XDZzc4Z That means, you will always get a single row from a table.
Thanks!
HEY, what does temp do?
it is just an alias given to the temporary table created because the table has to have an alias
such a pellucid explanation. Thank you :)
not work
Thank you for your explanation. I did not uderstand why we use min/max.Please explain
Thanks a bunch for this!!
Can you explain what exactly is happening in step2? What does 'set @' do? I tried running just the code in step 2 but couldn't understand.
wow! this is the best explanation i got so far.. just a few things why did we use min() and groupby rownumber.
wow! this is the best explanantion i found so far. just a few queries: why are we using min() and groupby rownumber in the end??
Awesome explanation! Much appreciated :)
Thanks for the breakdown, it really helps me to understand each concept.
hey, can someone explain why we use min/max here? thanks
min/max because we do not want the NULL elements.
When you use MIN/MAX in select statement, it will return a single row from the table with the LOWEST/HIGHEST value element from EACH column.
With GROUP BY clause, it will return the LOWEST/HIGHEST value element from each column and EACH group. Refer to the image attached on my main thread and connect this comment. You will get it.
Thanks a lot :) crisp explanation
Can you please explain what is use of "END AS" in line:: case when Occupation='Doctor' then Name end as Doctor
Each CASE statment when the condition is met returns a value. END AS is used to name column of that return value.
I confused dat line at start too, thought END AS together meant something LOL, END to close CASE statement and AS to add an alias
woooh!
You can improve readability using window functions
Thanks for giving code in Oracle, it was super confusing for me to see @r1 in MySql
You can use those code in MySql too
Thanks for the explaination, that's great!
Thank you so much for explaination and posting this :)
Thanks
Greate explanation, Thanks
Brilliant. Thanks !
Thanks for such a nice explanation
Thank you so much!!
Pretty clear, thanks!
Thankyou so much!
Hi, your code is giving me an error. Please help
unknown SET option "@r1=0," select case when Occupation='Doctor' then (@r1:=@r1+1) * ERROR at line 3: ORA-00936: missing expression
Wonderful explanation!! Thanks!
Great crack! Thank you btw!!
Great explaination thank you for writing this!
Thanks! Helped a lot
thanks so much
Here, can't we use pivot ? If not then WHY?
just wanted to make it as simple as that with basic sql , u can do wth pivot if u want !
okay, thankss
thank you for your explanation raiyanger24, I learn a lot
WOW!!!
Thanks
Excellant Explanation! Opened me to new type of problem solving. Thank you :D
Amazing! Thanks
what does the @r1=0 to @r4=0 means?
Very good explanation
great, thank you.
Thanks so much for a very clear explanation!
Thank you very much for the steps. Learned how to pivot rows and columns using mysql from your post.
BEST EXPLANATION..THANKS A TON!
Thanks! for detailed explanation
One of the most detailed explanation ever! Thanks.
Thanks for breaking down the problem so nicely that people could understand easily.
Too good man! Thanks
thanks! This is so helpful and informative! Great explanation.
thanks, sql magician!
Thanks!!Good Work
Great explaination, i had an idea to do like that but can't find a way to make it, you explained everything perfectly clear. Thank you!
Thank you for explaining it so beautifully. This is excellent for beginners.
Thank you so much!. Your explanation is awsome, I culdn't figure the solution out with out your example
But my output is comig wrong. Please tell me what to do. OUTPUT: Your Output (stdout) Aamina Ashley Christeen Eve
Thanks for the answer and clear explination
I'm a beginner and you saved my day, thanks
Thnx for the qeury
This is crazy detailed and clear. Thanks a lot!!
This has got to be the best explained comment in all of hacker rank i have seen yet. Kudos to you for going the extra mile to explain to us mere mortals.
This is briliant, thanks!
Really great explanation! Thanks!
I have some commnet about how to keep track at each row. How does it look when we use :
This is window function that automatically indexing each row follow our condition, it contain the same mechanism when we use
Since I see that we hasn't nessecery user variable here, I think we can simplify and avoid to use user variable where it really doesn't ineeded
SELECT MAX(DOCTORS), MAX(PROFESSORS), MAX(SINGERS), MAX(ACTORS) FROM
( SELECT ROW_NUMBER() OVER (PARTITION BY OCCUPATION ORDER BY NAME) AS ROWNUMBER,
FROM OCCUPATIONS ) AS SRC GROUP BY SRC.ROWNUMBER ORDER BY SRC.ROWNUMBER;
Thank you!
thanks:) It helped me a lot
Thank you so much, it is so clear and really explains a lot.
While I have a small doubt about the order by clause. Could anyone explain why the RowNumber that is set in the 'case when' statement will be sorted again? I thought that the ORDER BY clause is operated after the SELECT statement, so should not the RowNumber be set with the rows that name was not sorted yet? Exemplifying from raiyanger24's picture example that - Julia will still be in RowNumber of 1 for Doctor.even after an order by execution Thank you so much guys!
Did you find an answer to this? I'm confused here as well.
The spam blocker is getting me because I'm trying to copy and paste the code I used to investigate. I can still share the conclusion though:
Contrary to what one is taught, it seems not everything in
SELECT
is executed beforeORDER BY
. It seems that anytime you derive a column (usingCASE
, by doing arithmetic, etc.), that column is going to be formed off of the ordered version of the non-derived fields if the field for theORDER BY
clause is non-derived.You could've skipped everything upto step 3 with the help of window function.
Regardless, your comment was very helpful for me.
Can you explain this SELECT MIN(Doctor),MIN(Professor),MIN(Singer),MIN(Actor) why we are selecting min of all columns?
If we run the inner subquery, then it would return following result set
Since we want all the peoples for specific row_number() to appear in the same row, we are using group by. And, when using group by, we can either select the columns in the group by list, or use aggregate function. So, in my case I used MIN, but in this case doing, MAX would have given the same result.
thanks for the kind explation!
Thanks a lot, every beautiful and clear explanation. Do you have any youtube channel or blog about SQL or coding or data stuff,.. I wanna subcribe yours:))
awsome explanation just so up to point thanks a lot
Adding my voice to the chorus of thanks for this - thank you! It would have taken me a very long time to figure that out alone - I've really learned something from this exercise and your explanation.
tysm
Thank you!
phenomenal answer!
Very good answer