[1795_EASY] Rearrange Products Table

2022. 8. 2. 23:46·SQL/LeetCode

Table: Products

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| product_id  | int     |
| store1      | int     |
| store2      | int     |
| store3      | int     |
+-------------+---------+
product_id is the primary key for this table.
Each row in this table indicates the product's price in 3 different stores: store1, store2, and store3.
If the product is not available in a store, the price will be null in that store's column.

 

Write an SQL query 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.

Return the result table in any order.

The query result format is in the following example.

 

Example 1:

Input: 
Products table:
+------------+--------+--------+--------+
| product_id | store1 | store2 | store3 |
+------------+--------+--------+--------+
| 0          | 95     | 100    | 105    |
| 1          | 70     | null   | 80     |
+------------+--------+--------+--------+
Output: 
+------------+--------+-------+
| product_id | store  | price |
+------------+--------+-------+
| 0          | store1 | 95    |
| 0          | store2 | 100   |
| 0          | store3 | 105   |
| 1          | store1 | 70    |
| 1          | store3 | 80    |
+------------+--------+-------+
Explanation: 
Product 0 is available in all three stores with prices 95, 100, and 105 respectively.
Product 1 is available in store1 with price 70 and store3 with price 80. The product is not available in store2.

문제 조건 

 

각 행이(product_id, store,price)를 갖도록 Products 테이블을 재정렬 하시오.

해당 상점에 제품이 없는 경우 결과 테이블에 해당 product_id및 상점 조합이 있는 행을 포함하지 마시오.

 

풀이 과정 

select product_id ,
        'store1' store,
        store1 as 'price'
from products 
where store1 is not null

union

select product_id,
        'store2' store,
        store2 as 'price'
from products 
where store2 is not null

union

select product_id,
        'store3' store,
        store3 as 'price'
from products 
where store3 is not null

 

ORACLE 에서 UNPIVOT으로 풀어보기 

- UNPIVOT EXCLUDE NULLS? : NULL을 포함시키기 위함

 

https://dejavuhyo.github.io/posts/oracle-unpivot/

 

Oracle UNPIVOT

1. Oracle UNPIVOT Oracle UNPIVOT 절을 사용하면 열을 행으로 전환할 수 있다. UNPIVOT 절은 PIVOT 절과 반대이다. 단, 전치 과정 동안 데이터의 집계를 해제하지 않는다는 점이다.

dejavuhyo.github.io

SELECT 
    product_id,
    store,
    price
FROM Products 
UNPIVOT EXCLUDE NULLS (price FOR store IN (store1 AS 'store1', store2 AS 'store2', store3 AS 'store3'));

 

저작자표시 (새창열림)

'SQL > LeetCode' 카테고리의 다른 글

[1821#_EASY] Find Customers With Positive Revenue this Year  (0) 2022.08.03
[1809#_EASY] Ad-Free Sessions  (0) 2022.08.03
[1789#_EASY] Primary Department for Each Employee  (0) 2022.07.31
[1777#_EASY] Product's Price for Each Store  (0) 2022.07.31
[1757_EASY] Recyclable and Low Fat Products  (0) 2022.07.31
'SQL/LeetCode' 카테고리의 다른 글
  • [1821#_EASY] Find Customers With Positive Revenue this Year
  • [1809#_EASY] Ad-Free Sessions
  • [1789#_EASY] Primary Department for Each Employee
  • [1777#_EASY] Product's Price for Each Store
소금깨
소금깨
  • 소금깨
    고군분투 인생살이
    소금깨
  • 전체
    오늘
    어제
    • 분류 전체보기 (328)
      • SQL (271)
        • 프로그래머스 (27)
        • LeetCode (198)
        • Hacker Rank (27)
        • Solve SQL (1)
        • 개념 (15)
      • 데이터 분석 (2)
        • 참고하며 공부하기 (14)
      • 기타 (15)
        • 통계 (14)
      • 오류 (6)
      • TABLEAU (3)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    프리미엄
    solvesql
    HACKER_RANK
    파이썬을활용한시계열데이터분석
    해커랭크
    LeetCode
    SQL
    패스트캠퍼스후기
    medium
    파이썬을활용한시계열데이터분석AtoZ올인원패키지Online
    직장인자기계발
    easy
    패스트캠퍼스
    패캠챌린지
    프로그래머스
    MySQL
    Hard
    시계열데이터분석
    직장인인강
    group by
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
소금깨
[1795_EASY] Rearrange Products Table
상단으로

티스토리툴바

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.