๐Ÿ’ซ ๋ฌธ์ œ



ย 

๐Ÿ’ซ CODE

SELECT DATE_FORMAT(SALES_DATE, '%Y-%m-%d') AS SALES_DATE, PRODUCT_ID, USER_ID, SALES_AMOUNT
FROM (
  SELECT SALES_DATE, PRODUCT_ID, USER_ID, SALES_AMOUNT
  FROM ONLINE_SALE
  WHERE EXTRACT(YEAR FROM SALES_DATE) = 2022 AND EXTRACT(MONTH FROM SALES_DATE) = 3
  UNION ALL
  SELECT SALES_DATE, PRODUCT_ID, NULL AS USER_ID, SALES_AMOUNT
  FROM OFFLINE_SALE
  WHERE EXTRACT(YEAR FROM SALES_DATE) = 2022 AND EXTRACT(MONTH FROM SALES_DATE) = 3
) AS ONLINE_OFFLINE_SALE
ORDER BY SALES_DATE ASC, PRODUCT_ID ASC, COALESCE(USER_ID, -1) ASC;

ย 

๐Ÿ’ซ ํ’€์ด ์กฐ๊ฑด

1. 2022๋…„ 3์›”์˜ ์˜คํ”„๋ผ์ธ/์˜จ๋ผ์ธ ์ƒํ’ˆ ํŒ๋งค ๋ฐ์ดํ„ฐ
2. ํŒ๋งค ๋‚ ์งœ, ์ƒํ’ˆID, ์œ ์ €ID, ํŒ๋งค๋Ÿ‰ ์ถœ๋ ฅ
3. OFFLINE_SALE ํ…Œ์ด๋ธ”์˜ ํŒ๋งค ๋ฐ์ดํ„ฐ์˜ USER_ID ๊ฐ’์€ NULL ๋กœ ํ‘œ์‹œ
4. ํŒ๋งค์ผ์„ ๊ธฐ์ค€์œผ๋กœ ์˜ค๋ฆ„์ฐจ์ˆœ ์ •๋ ฌํ•ด์ฃผ์‹œ๊ณ  ํŒ๋งค์ผ์ด ๊ฐ™๋‹ค๋ฉด ์ƒํ’ˆ ID๋ฅผ ๊ธฐ์ค€์œผ๋กœ ์˜ค๋ฆ„์ฐจ์ˆœ, ์ƒํ’ˆID๊นŒ์ง€ ๊ฐ™๋‹ค๋ฉด ์œ ์ € ID๋ฅผ ๊ธฐ์ค€์œผ๋กœ ์˜ค๋ฆ„์ฐจ์ˆœ ์ •๋ ฌ

ย 

๐Ÿ’ซ ํ’€์ด

1. SELECT DATE_FORMAT(SALES_DATE, '%Y-%m-%d') AS SALES_DATE, PRODUCT_ID, USER_ID, SALES_AMOUNT
  • ํŒ๋งค ๋‚ ์งœ(SALES_DATE), ์ƒํ’ˆID(PRODUCT_ID), ์œ ์ €ID(USER_ID), ํŒ๋งค๋Ÿ‰(SALES_AMOUNT) ์กฐํšŒ
  • DATE_FORMAT(SALES_DATE, '%Y-%m-%d')์„ ์ด์šฉํ•ด์„œ ํŒ๋งค ๋‚ ์งœ(SALES_DATE)๊ฐ€ ๋…„-์›”-์ผ ๊นŒ์ง€๋งŒ ๋‚˜์˜ค๋„๋ก
2. FROM () AS ONLINE_OFFLINE_SALE
  • FROM์ ˆ์— AS๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ONLINE_OFFLINE_SALE ๋ณ„์นญ ์ง€์ •
3. SELECT SALES_DATE, PRODUCT_ID, USER_ID, SALES_AMOUNT FROM ONLINE_SALE WHERE EXTRACT(YEAR FROM SALES_DATE) = 2022 AND EXTRACT(MONTH FROM SALES_DATE) = 3
  • ONLINE_SALE ํ…Œ์ด๋ธ”์˜ ํŒ๋งค ๋‚ ์งœ(SALES_DATE), ์ƒํ’ˆID(PRODUCT_ID), ์œ ์ €ID(USER_ID), ํŒ๋งค๋Ÿ‰(SALES_AMOUNT) ์กฐํšŒ
  • EXTRACT()๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ๋…„๋„, ์›” ์ง€์ •
4. UNION ALL
  • ์ฟผ๋ฆฌ์˜ ๊ฒฐ๊ณผ๋ฅผ ํ•ฉ์ณ์คŒ, ์ค‘๋ณต์ œ๊ฑฐ x. <-> UNION๋งŒ ์ผ์„๋•Œ๋Š” ์ค‘๋ณต ์ œ๊ฑฐ O
5. SELECT SALES_DATE, PRODUCT_ID, NULL AS USER_ID, SALES_AMOUNT FROM OFFLINE_SALE WHERE EXTRACT(YEAR FROM SALES_DATE) = 2022 AND EXTRACT(MONTH FROM SALES_DATE) = 3
  • ONLINE_SALE ํ…Œ์ด๋ธ”์˜ ํŒ๋งค ๋‚ ์งœ(SALES_DATE), ์œ ์ €ID(USER_ID), ํŒ๋งค๋Ÿ‰(SALES_AMOUNT) ์กฐํšŒ
  • NULL๊ฐ’์˜ ๋ณ„์นญ์„ USER_ID๋กœ ์ง€์ •
  • EXTRACT()๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ๋…„๋„, ์›” ์ง€์ •
6. ORDER BY SALES_DATE ASC, PRODUCT_ID ASC, COALESCE(USER_ID, -1) ASC
  • ํŒ๋งค์ผ(SALES_DATE)์„ ๊ธฐ์ค€์œผ๋กœ ์˜ค๋ฆ„์ฐจ์ˆœ ์ •๋ ฌ, ํŒ๋งค์ผ(SALES_DATE)์ด ๊ฐ™๋‹ค๋ฉด ์ƒํ’ˆID(PRODUCT_ID)๋ฅผ ๊ธฐ์ค€์œผ๋กœ ์˜ค๋ฆ„์ฐจ์ˆœ, ์ƒํ’ˆID(PRODUCT_ID)๊นŒ์ง€ ๊ฐ™๋‹ค๋ฉด ์œ ์ €ID(USER_ID)๋ฅผ ๊ธฐ์ค€์œผ๋กœ ์˜ค๋ฆ„์ฐจ์ˆœ ์ •๋ ฌ
    -COALESCE()ํ•จ์ˆ˜๋ฅผ ์ด์šฉํ•˜์—ฌ USER_ID๊ฐ€ NULL์ด ์•„๋‹ˆ๋ฉด USER_ID๋ฅผ ๋ฐ˜ํ™˜ํ•˜๊ณ , NULL์ด๋ผ๋ฉด -1์„ ๋ฐ˜ํ™˜ํ•˜์—ฌ ์˜ค๋ฆ„์ฐจ์ˆœ ์ •๋ ฌ์„ ํ•˜๋„๋ก

By Dozzing

๋‹ต๊ธ€ ๋‚จ๊ธฐ๊ธฐ

์ด๋ฉ”์ผ ์ฃผ์†Œ๋Š” ๊ณต๊ฐœ๋˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค. ํ•„์ˆ˜ ํ•„๋“œ๋Š” *๋กœ ํ‘œ์‹œ๋ฉ๋‹ˆ๋‹ค