-
leetcode - 1777. Product's Price for Each StoreSQL 문제풀이 2022. 8. 1. 15:14
난이도 : Easy
Table: Products
+-------------+---------+ | Column Name | Type | +-------------+---------+ | product_id | int | | store | enum | | price | int | +-------------+---------+ (product_id, store) is the primary key for this table. store is an ENUM of type ('store1', 'store2', 'store3') where each represents the store this product is available at. price is the price of the product at this store.
Write an SQL query to find the price of each product in each store.
Return the result table in any order.
The query result format is in the following example.
Example 1:
Input: Products table: +-------------+--------+-------+ | product_id | store | price | +-------------+--------+-------+ | 0 | store1 | 95 | | 0 | store3 | 105 | | 0 | store2 | 100 | | 1 | store1 | 70 | | 1 | store3 | 80 | +-------------+--------+-------+ Output: +-------------+--------+--------+--------+ | product_id | store1 | store2 | store3 | +-------------+--------+--------+--------+ | 0 | 95 | 100 | 105 | | 1 | 70 | null | 80 | +-------------+--------+--------+--------+ Explanation: Product 0 price's are 95 for store1, 100 for store2 and, 105 for store3. Product 1 price's are 70 for store1, 80 for store3 and, it's not sold in store2.
WITH sub AS ( SELECT product_id , IF(store = 'store1', price, null) AS store1 , IF(store = 'store2', price, null) AS store2 , IF(store = 'store3', price, null) AS store3 FROM Products ) SELECT product_id , SUM(store1) store1 , SUM(store2) store2 , SUM(store3) store3 FROM sub GROUP BY 1
Accepted (14.80%)
SELECT * FROM Products PIVOT ( MAX(price) FOR store IN ( [store1] ,[store2] ,[store3] ) ) t1
Accepted (64.96%)
'SQL 문제풀이' 카테고리의 다른 글
leetcode - 1264. Page Recommendations (0) 2022.08.01 leetcode - 1795. Rearrange Products Table (0) 2022.08.01 leetcode - 1757. Recyclable and Low Fat Products (0) 2022.08.01 leetcode - 1212. Team Scores in Football TournamentMedium (0) 2022.07.30 leetcode - 1741. Find Total Time Spent by Each Employee (0) 2022.07.29