Created
April 10, 2021 22:10
-
-
Save Per48edjes/20db03e24ee31869c5be2c33a502f2cd to your computer and use it in GitHub Desktop.
Pivot entries in MySQL using variables and CASE statements
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- Set counter variables | |
set @r1=0, @r2=0, @r3=0, @r4=0; | |
with | |
cte_pivot as ( | |
select | |
case | |
when Occupation='Doctor' then (@r1:=@r1+1) | |
when Occupation='Professor' then (@r2:=@r2+1) | |
when Occupation='Singer' then (@r3:=@r3+1) | |
when Occupation='Actor' then (@r4:=@r4+1) | |
end as idx, | |
case when Occupation='Doctor' then Name end as Doctor, | |
case when Occupation='Professor' then Name end as Professor, | |
case when Occupation='Singer' then Name end as Singer, | |
case when Occupation='Actor' then Name end as Actor | |
from OCCUPATIONS | |
order by Name | |
) | |
select | |
min(Doctor), | |
min(Professor), | |
min(Singer), | |
min(Actor) | |
from cte_pivot | |
group by idx |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For application and associated problem, see Occupations question at HackerRank.