sqlcase

SQL question - why i can't solve a problem


Why my solution of a problem on the study site is not accepted and showing "wrong answer"?

Here is the problem - https://www.hackerrank.com/challenges/the-pads/problem/ :

Generate the following two result sets:

  1. 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).

  2. 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 a total of [occupation_count] [occupation]s.

where [occupation_count] is the number of occurrences of an occupation in OCCUPATIONS and [occupation] is the lowercase occupation name. If more than one Occupation has the same [occupation_count], they should be ordered alphabetically.

My query is:

SELECT 
    CAST(NAME, CASE 
                  WHEN occupation = 'Actor' THEN '(A)' 
                  WHEN occupation = 'Doctor' THEN '(D)' 
                  WHEN occupation = 'Professor' THEN '(P)' 
                  WHEN occupation = 'Singer' THEN '(S)' 
               END) 
FROM   
    occupations; 

and

SELECT 
    CASE 
       WHEN occupation = 'Actor' 
          THEN CONCAT('There are a total of ', COUNT(occupation), ' ', LOWER(occupation), 's.') 
       WHEN occupation = 'Doctor' 
          THEN CONCAT('There are a total of ', COUNT(occupation), ' ', LOWER(occupation), 's.') 
       WHEN occupation = 'Singer' 
          THEN CONCAT('There are a total of ', COUNT(occupation), ' ', LOWER(occupation), 's.') 
       WHEN occupation = 'Professor' 
          THEN CONCAT('There are a total of ', COUNT(occupation), ' ', LOWER(occupation), 's.') 
   END 
   FROM
       occupations 
   GROUP BY 
       occupation 
   ORDER BY 
       COUNT(occupation), occupation;  

The query has same output like in the example on HackerRank. What am I doing wrong?


Solution

  • Two issues:

    First query:

    SELECT   CONCAT(Name, '(', substr(Occupation, 1, 1), ')')
    FROM     Occupations
    ORDER BY Name;
    

    Your second query again expects a few static occupations but will return null when the occupation in the test data is not one of them. Don't use CASE here.

    SELECT   CONCAT('There are a total of ', COUNT(Occupation), ' ', LOWER(Occupation), 's.') 
    FROM     Occupations
    GROUP BY Occupation 
    ORDER BY COUNT(Occupation),
             Occupation;