I am trying to solve a question on HackerRank.
Here is my approach to solve the question:
select Concat(Name, '(', Substring(Occupation,1,1), ')') as pr
from Occupations
order by name;
select Concat('There are a total of',' ', count(*),' ',Occupation, 's.') as pr
from Occupations
group by Occupation
order by pr
This is the sample output of my query:
Ashely(P)
Christeen(P)
Jane(A)
Jenny(D)
Julia(A)
Ketty(P)
Maria(A)
Meera(S)
Priya(S)
Samantha(D)
There are a total of 2 doctors.
There are a total of 2 singers.
There are a total of 3 actors.
There are a total of 3 professors.
Why couldn't my code generate expected output?
Your approach of solving a problem was good. You can use this approach and it works in mysql but it doesn't work in oracle. Because, in Oracle, CONCAT function can take a maximum of 2 arguments to concatenate where as in mysql, CONCAT function can take multiple arguments. You can use nested concat statements as follows:
select concat(concat('There are a total of ', count(*)), concat(' ', occupation)) as pr from occupations group by occupation order by pr;
Else, use || to concat multiple strings as below:
select ('There are a total of '|| count(*) || ' ' || occupation || 's') as pr from occupations group by occupation order by pr;