SQL/LeetCode

[SQL] Rearrange Products Table(LeetCode/Oracle)

DBwiz 2023. 10. 29. 14:42

안녕하세요!

 

이번 포스팅은 LeetCode에 있는 Rearrange Products Table 문제를 OracleDB로 풀어보려고 합니다!

 

(모든 문제는 Oracle로 풀이하겠습니다.)

 

1. 문제 링크 : https://leetcode.com/problems/rearrange-products-table/description/

 

2. 문제

Column name Type
product_id int
store1 int
store2 int
store3 int
[문제] Write a solution to rearrange the Products table so that each row has (product_id, store, price). If a product is not available in a store, do not include a row with that product_id and store combination in the result table.

각 행(product_id, store, price)이 있도록 Products 테이블을 재배치하는 문제입니다.

 

3. 제출 쿼리 및 설명

 

1) 'store1'에 대한 값이 있는 PRODUCT_ID의 'store1'의 가격(price)를 조회합니다.

SELECT PRODUCT_ID, 'store1' AS STORE, STORE1 AS PRICE
FROM PRODUCTS 
WHERE STORE1 IS NOT NULL

2) 'store2'에 대한 값이 있는 PRODUCT_ID의 'store2'의 가격(price)를 조회합니다.

SELECT PRODUCT_ID, 'store2' AS STORE, STORE2 AS PRICE
FROM PRODUCTS 
WHERE STORE2 IS NOT NULL

 

3) 'store3'에 대한 값이 있는 PRODUCT_ID의 'store3'의 가격(price)를 조회합니다.

SELECT PRODUCT_ID, 'store3' AS STORE, STORE3 AS PRICE
FROM PRODUCTS 
WHERE STORE3 IS NOT NULL

최종) UNION을 활용해서 1,2,3번 쿼리를 모두 합칩니다.

SELECT PRODUCT_ID, 'store1' AS STORE, STORE1 AS PRICE
FROM PRODUCTS 
WHERE STORE1 IS NOT NULL
UNION
SELECT PRODUCT_ID, 'store2' AS STORE, STORE2 AS PRICE
FROM PRODUCTS 
WHERE STORE2 IS NOT NULL
UNION
SELECT PRODUCT_ID, 'store3' AS STORE, STORE3 AS PRICE
FROM PRODUCTS 
WHERE STORE3 IS NOT NULL
;