[SQL] 힘들땐...SQL을 봐...hackerrank 문제 정리(1)

JIEUN KANG·2020년 11월 24일
2


Revising the Select Query I
Query all columns for all American cities in the CITY table with populations larger than 100000. The CountryCode for America is USA.

SELECT * 
FROM CITY
WHERE POPULATION > 100000 
AND COUNTRYCODE = 'USA'
  • COUNTRYCODE == 'USA'라 했었는데 안되어서 깜짝놀랐다..

Revising the Select Query II
Query the NAME field for all American cities in the CITY table with populations larger than 120000. The CountryCode for America is USA.

SELECT NAME
FROM CITY
WHERE POPULATION > 120000
AND COUNTRYCODE = 'USA'

Select All
Query all columns (attributes) for every row in the CITY table.

SELECT *
FROM CITY
  • 본격 행복회로 가동 문제

Select By ID
Query all columns for a city in CITY with the ID 1661.

SELECT *
FROM CITY
WHERE ID = 1661

Weather Observation Station 3
Query a list of CITY names from STATION for cities that have an even ID number. Print the results in any order, but exclude duplicates from the answer.

SELECT DISTINCT CITY
FROM STATION
WHERE MOD(ID,2) = 0
SELECT DISTINCT CITY
FROM STATION
WHERE ID % 2 = 0
  • 바로 생각나는건 % 를 써서 나머지가 0인걸 찾는 것인듯..

Weather Observation Station 4
Find the difference between the total number of CITY entries in the table and the number of distinct CITY entries in the table.

SELECT COUNT(CITY) - COUNT(DISTINCT(CITY))
FROM STATION 
  • COUNT와 DISTINCT의 위치를 한참 헷갈렸었고 지금도 헷갈리는 문제...

Weather Observation Station 5
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.

(SELECT CITY, LENGTH(CITY)
FROM STATION
WHERE LENGTH(CITY) = (SELECT MIN(LENGTH(CITY))
                      FROM STATION)
ORDER BY CITY ASC
LIMIT 1)

UNION

(SELECT CITY, LENGTH(CITY)
FROM STATION
WHERE LENGTH(CITY) = (SELECT MAX(LENGTH(CITY))
                      FROM STATION)
ORDER BY CITY ASC
LIMIT 1)
                    
  • 고민하게 되는 포인트(1) : WHERE절 서브쿼리 어떤식으로 걸었더라?
  • 고민하게 되는 포인트(2) : UNION 걸때 ORDER BY 어떤식으로 하지?
  • 하나씩 뽑아야 하서 LIMIT 1 했는데 더 현명한 방법도 있을거같기도 하고...
profile
가장 보통의 존재

0개의 댓글