[LeetCode] List the Products Ordered in a Period

아르당·2026년 4월 21일

LeetCode

목록 보기
274/303
post-thumbnail

문제를 이해하고 있다면 바로 풀이를 보면 됨
전체 코드로 바로 넘어가도 됨
마음대로 번역해서 오역이 있을 수 있음

Problem

Table: Products

Column NameType
prouct_idint
product_idvarchar
product_categoryvarchar

product_id는 이 테이블의 기본 키이다.
테이블은 회사의 제품에 대한 데이터를 포함한다.

Table: Orders

Column NameType
product_idint
order_datedate
unitint

테이블은 중복된 행을 가질 수 있다.
product_id는 Products 테이블의 외래키이다.
unit는 order_date에 주문된 제품의 수량이다.

2020년에 2월에 최소 100개 이상 주문된 제품의 이름과 수량을 구하는 방법을 작성해라.

Example

Input:
Product table:

product_idproduct_nameproduct_category
1Leetcode SolutionsBook
2Jewels of StringologyBook
3HPLaptop
4LenovoLaptop
5Leetcode KitT-shirt

Orders table:

product_idorder_dateunit
12020-02-0560
12020-02-1070
22020-01-1830
22020-02-1180
32020-02-172
32020-02-243
42020-03-0120
42020-03-0430
42020-03-0460
52020-02-2550
52020-02-2750
52020-03-0150

Output:

product_nameunit
Leetcode Solutions130
Leetcode100

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개가 주문됐다.

Solved

-- 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
profile
내 마음대로 코드 작성하는 세상

0개의 댓글