The PADS [HackerRank]


Problem Link


https://www.hackerrank.com/challenges/the-pads/problem?isFullScreen=true

問題の説明


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 ocurrences 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.
Note: There will be at least two entries in the table for each type of occupation.
Input Format
The OCCUPATIONS table is described as follows:

入力フォーマット



入力例



サンプル出力

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.

答え(MySQL)

SELECT CONCAT(name, '(',SUBSTRING(occupation,1,1),')') FROM OCCUPATIONS ORDER BY name;

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

解説

CONCAT():2つ以上の文字列または列の値を1つの文字列に結合する関数.パラメータの数は2つを超えることができます.SUBSTRING(string_expression, start,length):文字列の場合、開始点(インデックス)から長さで切り捨てられます.(startは正数または負数、正数は1から終わり、負数は後ろから切り始める)LOWER():小文字の関数に変換されます.

参考資料


https://www.w3schools.com/sql/func_mysql_substring.asp