문제

Query the two cities in STATION with the shortest and longest CITY names, as well as their respective lengths (i.e.: number of characters in the name). If there is more than one smallest or largest city, choose the one that comes first when ordered alphabetically.

When ordered alphabetically, the CITY names are listed as ABC, DEF, PQRS, and WXY, with lengths 3, 3, 4 and 3. The longest name is PQRS, but there are 3 options for shortest named city. Choose ABC, because it comes first alphabetically.

 

 

 

city 이름 길이가 가장 짧은 도시, 가장 긴 도시를 출력하는 문제

limit을 사용하면 쉽게 구할 수 있다.

 

 

풀이 코드

order by를 사용해서 도시 이름 길이에 따라 오름차순, 내림차순으로 각각 나열한 후 limit 1을 걸어주면 가장 짧은 길이의 이름을 가진 도시와 가장 긴 길이의 이름을 가진 도시가 출력된다.

문제

Two pairs (X1, Y1) and (X2, Y2) are said to be symmetric pairs if X1 = Y2 and X2 = Y1.
Write a query to output all such symmetric pairs in ascending order by the value of X. List the rows such that X1 ≤ Y1.

 

*

Join문을 활용해서 구할 수 있는 문제이다.

 

 

실행 코드

 

1) X!=Y, 즉 X<Y인 케이스 -> INNER JOIN으로 짝 구하기

2) X=Y 인 케이스 -> HAVING COUNT(*) >= 2 조건을 추가해서 짝 구하기

 

두 가지 케이스를 UNION으로 합쳐주면 간단하게 풀 수 있다.

문제

Given the table schemas below, write a query to print the company_code, founder name, total number of lead managers, total number of senior managers, total number of managers, and total number of employees. Order your output by ascending company_code.

 

 

 

실행 코드

 

5개의 테이블을 LEFT JOIN으로 줄줄이 연결해주면 된다.

문제

Write a query to output the names of those students whose best friends got offered a higher salary than them. Names must be ordered by the salary amount offered to the best friends. It is guaranteed that no two students got same salary offer.

*

 

 

실행 코드

 

3개의 테이블이 제시되어 있는데, 먼저 본인을 기준으로 연봉 테이블을 구해준 뒤, 본인의 친구 기준으로 연봉 테이블을 연결해주어야 한다.

나는 from절에서 서브쿼리를 사용해서 조건을 추가했다.

 

1. 서브쿼리를 통해 본인의 연봉 제시

2. 본 쿼리에서 'INNER JOIN Packages P ON P.ID = A.Friend_ID' 구문을 추가하여 친구의 연봉 구분한 후 WHERE절로 비교

 

 

문제

Julia just finished conducting a coding contest, and she needs your help assembling the leaderboard! Write a query to print the respective hacker_id and name of hackers who achieved full scores for more than one challenge. Order your output in descending order by the total number of challenges in which the hacker earned a full score. If more than one hacker received full scores in same number of challenges, then sort them by ascending hacker_id.

 

1. 2개 이상의 챌린지 성공 및 만점 획득한 hacker를 찾아야 한다.

2. Difficulty테이블에서 difficulty_level에 따른 score와 hacker들이 획득한 score, difficulty_level이 일치하는지 확인해야 한다.

 

총 4개의 테이블이 있으며, 이들을 모두 inner_join 해준 후 차례대로 조건을 걸어주면 된다.

 

 

실행 코드

HAVING COUNT(H.HACKER_ID) > 1 조건을 추가해서 2개 이상의 챌린지를 한 hacker를 찾아주었다.

테이블이 4개라서 join절을 작성한 구문이 조금 복잡하다고 느껴지는데, 코드를 뜯어보면 전혀.. 그렇지 않다!

 

You are given two tables: Students and Grades. Students contains three columns ID, Name and Marks.

 

Students

 

Grades contains the following data

 

Ketty gives Eve a task to generate a report containing three columns: Name, Grade and Mark. Ketty doesn't want the NAMES of those students who received a grade lower than 8. The report must be in descending order by grade -- i.e. higher grades are entered first. If there is more than one student with the same grade (8-10) assigned to them, order those particular students by their name alphabetically. Finally, if the grade is lower than 8, use "NULL" as their name and list them by their grades in descending order. If there is more than one student with the same grade (1-7) assigned to them, order those particular students by their marks in ascending order. Write a query to help Eve.

 

Students 테이블과 Grades 테이블을 활용하여 학생별 Marks를 Grade 등급 구간별로 구분한 후, 출력하면 되는 문제이다.

이 문제를 풀면서 join문에 따로 조건절을 넣어서 사용할 수 있다는 걸 처음 알았다..! 항상 공통적으로 가지고 있는 외래키 연결하는 용도로만 사용했어서.. 덕분에 지식 하나 습득했다!

 

-

 

 

풀이 코드

students의 marks 점수를 grades테이블을 활용해서 구간별로 구분해주면 된다.

s.marks between g.min_mark and g.max_mark < marks가 min_mark, max_mark 구간에 따라 매치되면서 본인과 맞는 grade를 부여받는다.

 

 

 

 

1. Weather Observation Station 6

Query the list of CITY names starting with vowels (i.e., a, e, i, o, or u) from STATION. Your result cannot contain duplicates.

 

 

2. Weather Observation Station 7

Query the list of CITY names ending with vowels (a, e, i, o, u) from STATION. Your result cannot contain duplicates.

 

 

3. Weather Observation Station 8

Query the list of CITY names from STATION which have vowels (i.e., a, e, i, o, and u) as both their first and last characters. Your result cannot contain duplicates.

 

 

 

4. Weather Observation Station 18

Consider P1(a,c) and P2(b,d) to be two points on a 2D plane.
 a happens to equal the minimum value in Northern Latitude (LAT_N in STATION).
 b happens to equal the minimum value in Western Longitude (LONG_W in STATION).
 c happens to equal the maximum value in Northern Latitude (LAT_N in STATION).
 d happens to equal the maximum value in Western Longitude (LONG_W in STATION).
Query the Manhattan Distance between points  P1 and P2 and round it to a scale of 4 decimal places.

 

 

5. Weather Observation Station 19

Consider  P1(a,c) and P2(b, d) to be two points on a 2D plane where  (a,b) are the respective minimum and maximum values of Northern Latitude (LAT_N) and  (c,d) are the respective minimum and maximum values of Western Longitude (LONG_W) in STATION.
Query the Euclidean Distance between points  P1 and  P2 and format your answer to display  4 decimal digits.

 

 

Occupations

The first column is an alphabetically ordered list of Doctor names.
The second column is an alphabetically ordered list of Professor names.
The third column is an alphabetically ordered list of Singer names.
The fourth column is an alphabetically ordered list of Actor names.
The empty cell data for columns with less than the maximum number of names per occupation (in this case, the Professor and Actor columns) are filled with NULL values.

* The output column headers should be Doctor, Professor, Singer, and Actor, respectively.

Sample Input

 

 

풀이 코드

 

- CASE WHEN 문을 통해 피벗테이블을 생성한다.

- 같은 열에 동일 직업을 가진 사람들의 이름을 넣어야 한다. ROW_NUMBER() OVER (PARTITION BY ~ ORDER BY)절을 사용해서 문제를 풀어야 한다. * 서브쿼리의 경우 Alias 명칭을 제대로 부여해야 오류가 나지 않는다.

 

 

-

 

 

The PADS.

  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 ocurrences of each occupation in OCCUPATIONS. Sort the occurrences in ascending order, and output them in the following format:
    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.
  3. There are a total of [occupation_count] [occupation]s.

 

*

occupations 테이블에 있는 name + occupation의 첫 글자를 함께 출력하고, occupation을 count하여 문장을 출력해주는 문제이다.

 

 

 

풀이 코드

- LEFT(occupation, 1) -> SUBSTRING(occupation, 1, 1) 대체 가능하다.

SUBSTRING(occupation, 1, 1) : occupation의 첫 번째에 위치한 글자부터 1글자만 자른다는 뜻으로 해석할 수 있다.

- CONCAT으로 필요한 문자열과 변수를 연결해줘야 한다.

- 각각의 SELECT문에 서로 다른 정렬 기준을 주어야 한다.

- 두 번째 SELECT문은 COUNT함수를 사용하므로 GROUP BY(occupation) 함수를 사용해야 한다.

 

 

*

해커랭크는 문제가 모두 영어라서 문제해석을 정확하게 했느냐...가 관건인 듯하다.

'Data > SQL' 카테고리의 다른 글

[HackerRank] The Report  (0) 2023.02.15
[HackerRank] SQL Basic 문제 풀이 (MySQL)  (0) 2023.02.08
[SQLZOO] JOIN 문제 풀이  (0) 2023.02.01
[프로그래머스] SQL Kit 문제 풀이(2)  (0) 2023.01.29
[프로그래머스] SQL Kit 문제 풀이(1)  (1) 2023.01.28

+ Recent posts