본문 바로가기

컴퓨터과학/Algorithm

[SQL] [Codewars] 7Kyu - SQL with LOTR: Elven Wildcards

 

 

Codewars: Achieve mastery through coding challenge

Codewars is a coding practice site for all programmers where you can learn various programming languages. Join the community and improve your skills in many languages!

www.codewars.com

문제

Deep within the fair realm of Lothlórien, you have been asked to create a shortlist of candidates for a recently vacated position on the council.

Of so many worthy elves, who to choose for such a lofty position? After much thought you decide to select candidates by name, which are often closely aligned to an elf's skill and temperament.

Choose those with tegil appearing anywhere in their first name, as they are likely to be good calligraphers, OR those with astar anywhere in their last name, who will be faithful to the role.

Elves table:

 

  • firstname
  • lastname

all names are in lowercase

To aid the scribes, return the firstname and lastname column concatenated, separated by a space, into a single shortlist column, and capitalise the first letter of each name.

 

코드

SELECT
  INITCAP(firstname)||' '||INITCAP(lastname) AS shortlist
FROM Elves
WHERE
  firstname LIKE '%tegil%' OR lastname LIKE '%astar%'

 

설명

먼저, 문제에선 first name에 tegil이 들어가거나 last name에 astar가 들어가는 엘프들의 목록을 추출하라고 제시한다.
WHERE절에서 LIKE와 '%'를 활용하여 특정 문자의 포함 여부를 선택할 수 있다.


'%A'는 A로 끝나는 모든 것을, 'A%'는 A로 시작하는 모든 것을 조회한다는 의미를 가지고 있다. '%A%'는 A가 들어가는 모든 것을 조회한다.

 

그 후, 문제에선, 각각 첫 글자는 대문자여야 하고, firstname 칼럼과 lastname 칼럼을 공백을 사이에 두고 합치라는 주문을 한다. 첫 글자만 대문자로 만드는 명령어는 INITCAP이다. 참고로 모든 문자를 소문자로 출력하는 명령어는 LOWER(), 모든 문자를 대문자로 출력하는 명령어는 UPPER()이다.

 

본인은 이렇게 풀었지만,

SELECT INITCAP(firstname)||' '||INITCAP(lastname) AS shortlist

이렇게 한 번에 묶어주어도 잘 작동하며,

SELECT INITCAP(firstname || ' ' || lastname) AS shortlist

아예 || 대신 CONCAT으로 묶어버리는 것도 깔끔하다.

SELECT INITCAP(CONCAT(firstname, ' ', lastname)) AS shortlist