오늘은 그동안 프로그래머스에서 기본기를 다시 복습하면서 이제 LeetCode에 2주 Plan 에 DataBase 항목이 있었다. 따라서 나는 이 Plan에 맞게 습득하면서 추가로 배울 수 있으면 더 추가할 예정이다.
LeetCode 홈페이지 : https://leetcode.com/
LeetCode - The World's Leading Online Programming Learning Platform
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
이번에 학습하려는 Plan은 1차적으로 Study Plan 을 제공해주는 이 페이지부터 차근차근 접근하려고 한다. 이 문제 뿐만 아니라 추가적인 학습을 진행하고자 한다.
https://leetcode.com/study-plan/sql/?progress=xpksnh3c
SQL - Study Plan - LeetCode
SQL (Structured Query Language) is used to manage relational database management systems (RDBMS). The scope of SQL includes data insertion, query, update and deletion, database schema creation and modification, and data access control.
leetcode.com
Table: World
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| name | varchar |
| continent | varchar |
| area | int |
| population | int |
| gdp | int |
+-------------+---------+
name is the primary key column for this table.
Each row of this table gives information about the name of a country, the continent to which it belongs, its area, the population, and its GDP value.
A country is big if:
- it has an area of at least three million (i.e., 3000000 km2), or
- it has a population of at least twenty-five million (i.e., 25000000).
Write an SQL query to report the name, population, and area of the big countries.
Return the result table in any order.
The query result format is in the following example.
Example 1:
Input:
World table:
+-------------+-----------+---------+------------+--------------+
| name | continent | area | population | gdp |
+-------------+-----------+---------+------------+--------------+
| Afghanistan | Asia | 652230 | 25500100 | 20343000000 |
| Albania | Europe | 28748 | 2831741 | 12960000000 |
| Algeria | Africa | 2381741 | 37100000 | 188681000000 |
| Andorra | Europe | 468 | 78115 | 3712000000 |
| Angola | Africa | 1246700 | 20609294 | 100990000000 |
+-------------+-----------+---------+------------+--------------+
Output:
+-------------+------------+---------+
| name | population | area |
+-------------+------------+---------+
| Afghanistan | 25500100 | 652230 |
| Algeria | 37100000 | 2381741 |
+-------------+------------+---------+
이 문제는 Select에 기본적인 Where 문장이다 조건은 2개로 or 절로 구분할 수 있다.
select name , population,area from World where area>=3000000 or population>=25000000;
지역크기가 3마일보다 크거나 '또는' 인구수가 2500만명 이상 조건의 맞는 데이터들을 추출할 수 있다.
Table: Products
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| product_id | int |
| low_fats | enum |
| recyclable | enum |
+-------------+---------+
product_id is the primary key for this table.
low_fats is an ENUM of type ('Y', 'N') where 'Y' means this product is low fat and 'N' means it is not.
recyclable is an ENUM of types ('Y', 'N') where 'Y' means this product is recyclable and 'N' means it is not.
Write an SQL query to find the ids of products that are both low fat and recyclable.
Return the result table in any order.
The query result format is in the following example.
Example 1:
Input:
Products table:
+-------------+----------+------------+
| product_id | low_fats | recyclable |
+-------------+----------+------------+
| 0 | Y | N |
| 1 | Y | Y |
| 2 | N | Y |
| 3 | Y | Y |
| 4 | N | N |
+-------------+----------+------------+
Output:
+-------------+
| product_id |
+-------------+
| 1 |
| 3 |
+-------------+
Explanation: Only products 1 and 3 are both low fat and recyclable.
이 문장에서 핵심은 low_fats(저지방) 및 recyclable(재활용)이 가능한 product_id를 추출하는 문제이다.
기존 위에서 는 or 조건을 사용했지만 이번 문장은 2개가 같이 포함되어야한다
필자는
select product_id from products where low_fats='Y' and recyclable='Y' 로 작성을 하였다 하지만 이 문장도 가능하지만 위에 테이블 구성에서 enum으로 구성된 속성이 2개가 있다.
따라서 출력하고자 하는 값은 Y인 데이터만 필요하므로 조건문을 True로 바꿔도 실행 가능하다.
select product_id from products where low_fats=True and recyclable=True
Table: Customer
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| id | int |
| name | varchar |
| referee_id | int |
+-------------+---------+
id is the primary key column for this table.
Each row of this table indicates the id of a customer, their name, and the id of the customer who referred them.
Write an SQL query to report the names of the customer that are not referred by the customer with id = 2.
Return the result table in any order.
The query result format is in the following example.
Example 1:
Input:
Customer table:
+----+------+------------+
| id | name | referee_id |
+----+------+------------+
| 1 | Will | null |
| 2 | Jane | null |
| 3 | Alex | 2 |
| 4 | Bill | null |
| 5 | Zack | 1 |
| 6 | Mark | 2 |
+----+------+------------+
Output:
+------+
| name |
+------+
| Will |
| Jane |
| Bill |
| Zack |
+------+
이 문장은 조건이 심플하다 참조하는 id가 2가 아닌 데이터들만 출력해야한다.not referred by the customer with id = 2.
select name from customer where referee_id !=2 or referee_id is null;
우선 기초를 배우는 사람이 보았을때 referee_id !=2 인것은 이해할 수 있을 것이다. 하지만 뒷부분 referee_id is null 같은 경우 현재 테이블에서 참조하지않는 null값이 있다. 이 값(null)이 출력시키기 위해서는 is null명령어가 필요하다.
반대로 null을 출력시키기 싫은 경우 is not null로 활용할 수 있다.
Table: Customers
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| id | int |
| name | varchar |
+-------------+---------+
id is the primary key column for this table.
Each row of this table indicates the ID and name of a customer.
Table: Orders
+-------------+------+
| Column Name | Type |
+-------------+------+
| id | int |
| customerId | int |
+-------------+------+
id is the primary key column for this table.
customerId is a foreign key of the ID from the Customers table.
Each row of this table indicates the ID of an order and the ID of the customer who ordered it.
Write an SQL query to report all customers who never order anything.
Return the result table in any order.
The query result format is in the following example.
Example 1:
Input:
Customers table:
+----+-------+
| id | name |
+----+-------+
| 1 | Joe |
| 2 | Henry |
| 3 | Sam |
| 4 | Max |
+----+-------+
Orders table:
+----+------------+
| id | customerId |
+----+------------+
| 1 | 3 |
| 2 | 1 |
+----+------------+
Output:
+-----------+
| Customers |
+-----------+
| Henry |
| Max |
+-----------+
여기서 조건은 주문한적이 없는 고객명을 뽑아야 한다. Orders table에 id값이 없는것을 출력하면 된다.
처음에 필자는 그동안 프로그래머스에서 두 테이블 중 일부값을 출력하기 위해 Left Join을 많이 활용하였다. 따라서 처음 버전으로
SELECT cu.name as 'Customers' FROM customers AS cu LEFT JOIN Orders AS O ON cu.ID = O.CUSTOMERID WHERE O.CUSTOMERID IS NULL; 로 작성할 수 있었다.
하지만 이 방법말고도 not in 명령어를 활용하여 풀 수 있다.
SELECT name AS Customers
FROM customers
WHERE customers.id NOT IN
(
SELECT customerId from Orders
);
금일 총 4개 문제를 풀었는데 프로그래머스에서 배웠던 지식이 많이 도움이 되었다. Left join을 쉽게 활용할 줄 알았고 보다 효율적인 코드를 작성하기 위해 구현하는 방법 중 여러가지 명령어를 알 수 있게 되었다. 다음에는 2번째 섹터로 진행하고자 한다.
'군대 활동 > 공부' 카테고리의 다른 글
SQL 공부 (leetcode 2편) (0) | 2022.10.07 |
---|---|
알고리즘 공부 Leetcode Day4 (0) | 2022.10.06 |
leetcode 공부 Day3 (BinarySearch Final) (0) | 2022.10.04 |
leetcode 알고리즘 공부 Day2 (0) | 2022.10.02 |
SQL공부 4일차 (0) | 2022.10.02 |