Growth ๐ŸŒณ/Practice ๐Ÿ’ป

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ์˜คํ”„๋ผ์ธ/์˜จ๋ผ์ธ ํŒ๋งค ๋ฐ์ดํ„ฐ ํ†ตํ•ฉํ•˜๊ธฐ (2์ฐจ ํ’€์ด)

์ธ” 2023. 1. 13. 07:00

๐Ÿ“ข ๋ณธ ํฌ์ŠคํŒ…์€ Growth/Practice ๊ฒŒ์‹œ๊ธ€ (https://sy038680.tistory.com/232๋ฌธ์ œ์— ๋Œ€ํ•œ 2์ฐจ ํ’€์ด์ž…๋‹ˆ๋‹ค.

 


๊ธฐ์กด์—๋Š” UNION์„ ํ™œ์šฉํ•˜๊ธด ํ–ˆ๋Š”๋ฐ WITH์ ˆ์„ ์‚ฌ์šฉํ•ด์„œ ์ž„์‹œํ…Œ์ด๋ธ” T1์„ ์ƒ์„ฑํ•ด์„œ 

WHERE์กฐ๊ฑด(3์›” ํŒ๋งค), ์ •๋ ฌ์กฐ๊ฑด๋งŒ ๋‚˜์ค‘์œผ๋กœ ๋นผ์ฃผ์—ˆ๋‹ค.

 

์žฌํ’€์ด์—์„œ๋Š” ์•„์˜ˆ 3์›” ์กฐ๊ฑด๊นŒ์ง€ ์˜จ/์˜คํ”„๋ผ์ธ ํ…Œ์ด๋ธ”์— ๊ฐ๊ฐ ์ ์šฉํ•ด์ฃผ๊ณ  ๋‚œ ๋’ค์— UNION์„ ์ ์šฉํ–ˆ๋‹ค.

SELECT DATE_FORMAT(SALES_DATE,'%Y-%m-%d') AS SALES_DATE, PRODUCT_ID, USER_ID, SALES_AMOUNT
 FROM ONLINE_SALE
 WHERE SALES_DATE BETWEEN '2022-03-01 00:00:00' AND '2022-03-31 23:59:59'

UNION

SELECT DATE_FORMAT(SALES_DATE,'%Y-%m-%d') AS SALES_DATE, PRODUCT_ID, 
NULL AS USER_ID, SALES_AMOUNT
 FROM OFFLINE_SALE
 WHERE SALES_DATE BETWEEN '2022-03-01 00:00:00' AND '2022-03-31 23:59:59'

ORDER BY 1, 2, 3

 

 

ํ’€๊ณ ๋ณด๋‹ˆ ์ž„์‹œ ํ…Œ์ด๋ธ” ์™ธ์— ๊ธฐ์กด ํ’€์ด์™€ ํฐ ์ฐจ์ด๋Š” ์—†๋Š” ๊ฒƒ ๊ฐ™๋‹ค ๐Ÿ˜ฅ..

 


(๊ธฐํƒ€ ์ถ”๊ฐ€) ๋ฌธ์ œ ํ’€์ด ํ›„ UNION์— ๋Œ€ํ•ด ์ฐพ์•„๋ณด๋‹ค๊ฐ€ ์•Œ๊ฒŒ ๋œ ๋ฐฐ์›€

 

์œ„ ๋ฌธ์ œ์—์„œ๋Š” ORDER BY๋Š” ์ฟผ๋ฆฌ ๊ฐ€์žฅ ๋งˆ์ง€๋ง‰์— ์ž‘์„ฑํ•˜๊ณ  ์ •๋ ฌ ์กฐ๊ฑด์„ ์ ์šฉํ–ˆ๋Š”๋ฐ

> ๊ฐ๊ฐ ์ •๋ ฌ์กฐ๊ฑด์„ ์ฃผ๊ณ  ํ•ฉ์น˜๊ณ  ์‹ถ๋‹ค๋ฉด?

๊ฐ SELECT ์ ˆ์— ๊ฐ๊ฐ ์ •๋ ฌ ์กฐ๊ฑด์„ ์ฃผ๊ณ 

(SELECT ~ FROM ~ ORDER BY โ‘  ) UNION (SELECT ~ FROM ~ ORDER BY โ‘ก) ๋กœ ์ž‘์„ฑํ•˜๋ฉด ๋œ๋‹ค.

 

์ž‘์„ฑ ์˜ˆ์‹œ)

(SELECT DATE_FORMAT(SALES_DATE,'%Y-%m-%d') AS SALES_DATE, PRODUCT_ID, USER_ID, SALES_AMOUNT
 FROM ONLINE_SALE
 WHERE SALES_DATE BETWEEN '2022-03-01 00:00:00' AND '2022-03-31 23:59:59'
 ORDER BY 1 DESC, 2, 3 DESC)
 
UNION

(SELECT DATE_FORMAT(SALES_DATE,'%Y-%m-%d') AS SALES_DATE, PRODUCT_ID, 
NULL AS USER_ID, SALES_AMOUNT
 FROM OFFLINE_SALE
 WHERE SALES_DATE BETWEEN '2022-03-01 00:00:00' AND '2022-03-31 23:59:59'
 ORDER BY 1, 2, 3)