문제를 이해하고 있다면 바로 풀이를 보면 됨
전체 코드로 바로 넘어가도 됨
마음대로 번역해서 오역이 있을 수 있음
Table: Products
| Column Name | Type |
|---|---|
| prouct_id | int |
| product_id | varchar |
| product_category | varchar |
product_id는 이 테이블의 기본 키이다.
테이블은 회사의 제품에 대한 데이터를 포함한다.
Table: Orders
| Column Name | Type |
|---|---|
| product_id | int |
| order_date | date |
| unit | int |
테이블은 중복된 행을 가질 수 있다.
product_id는 Products 테이블의 외래키이다.
unit는 order_date에 주문된 제품의 수량이다.
2020년에 2월에 최소 100개 이상 주문된 제품의 이름과 수량을 구하는 방법을 작성해라.
Input:
Product table:
| product_id | product_name | product_category |
|---|---|---|
| 1 | Leetcode Solutions | Book |
| 2 | Jewels of Stringology | Book |
| 3 | HP | Laptop |
| 4 | Lenovo | Laptop |
| 5 | Leetcode Kit | T-shirt |
Orders table:
| product_id | order_date | unit |
|---|---|---|
| 1 | 2020-02-05 | 60 |
| 1 | 2020-02-10 | 70 |
| 2 | 2020-01-18 | 30 |
| 2 | 2020-02-11 | 80 |
| 3 | 2020-02-17 | 2 |
| 3 | 2020-02-24 | 3 |
| 4 | 2020-03-01 | 20 |
| 4 | 2020-03-04 | 30 |
| 4 | 2020-03-04 | 60 |
| 5 | 2020-02-25 | 50 |
| 5 | 2020-02-27 | 50 |
| 5 | 2020-03-01 | 50 |
Output:
| product_name | unit |
|---|---|
| Leetcode Solutions | 130 |
| Leetcode | 100 |
Explanation:
Products의 product_id = 1은 2월에 총 (60 + 70) = 130개가 주문됐다.
Products의 product_id = 2은 2월에 총 80개가 주문됐다.
Products의 product_id = 3은 2월에 총 (2 + 3) = 5개가 주문됐다.
Products의 product_id = 4은 2020년 2월에 주문되지 않았다
Products의 product_id = 5은 2월에 총 (50 + 50) = 100개가 주문됐다.
-- Write your PostgreSQL query statement below
select A.product_name, sum(B.unit) as unit
from Products A
join Orders B on A.product_id = B.product_id
where B.order_date between date '2020-02-01' and date '2020-02-29'
group by A.product_name
having sum(B.unit) >= 100