skip to Main Content

I need to generate the following two result sets:

Query an alphabetically ordered list of all names in OCCUPATIONS, immediately followed by the first letter of each profession as a parenthetical (i.e.: enclosed in parentheses).
For example: AnActorName(A), ADoctorName(D), AProfessorName(P), and ASingerName(S).

Query the number of occurrences of each occupation in OCCUPATIONS. Sort the occurrences in ascending order, and output them in the following format:

There are total [occupation_count] [occupation]s.

Table Name: Occupations

Total Columns: Two = ‘Name’ and ‘Occupation’,
demo table is shown below:

Table: Occupations
enter image description here

Sample Output:

Ashely(P)
Christeen(P)
Jane(A)
Jenny(D)
Julia(A)
Ketty(P)
Maria(A)
Meera(S)
Priya(S)
Samantha(D)
There are total 2 doctors.
There are total 2 singers.
There are total 3 actors.
There are total 3 professors.

My Approach

SELECT CONCAT(NAME,' ', '(',UPPER(SUBSTR(occupation,1,1)),')') AS occupation 
FROM OCCUPATIONS 
ORDER BY NAME;
SELECT CONCAT('There are a total of',' ',COUNT(occupation),' ', LOWER(occupation),'s','.') AS OCCUPATION_COUNT 
FROM OCCUPATIONS 
GROUP BY OCCUPATION 
ORDER BY COUNT(OCCUPATION) ASC;

I don’t know why it’s error

2

Answers


  1. I don’t found any issue in your query. Please share the MySQL version.

    You can update your 2nd query for a better output, as follows:

    SELECT CONCAT('There are a total of',' ',COUNT(occupation),' ', LOWER(occupation),IF(COUNT(occupation)>1, 's', ''),'.') AS OCCUPATION_COUNT 
    FROM OCCUPATIONS 
    GROUP BY OCCUPATION 
    ORDER BY COUNT(OCCUPATION) ASC;
    

    attached db<>fiddle code for reference.

    Login or Signup to reply.
  2. Your approach is completely fine and should not raise any error

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search