- Union์ ํ
์ด๋ธ์ ์์ง ๋ฐฉํฅ์ผ๋ก ํฉ์น๋ค
- ์ด๋ union์ ์ค๋ณต row๋ฅผ ์ ๊ฑฐํ์ง๋ง, union all ์ ์ค๋ณต row๋ฅผ ์ ๊ฑฐํ์ง ์๋๋ค.
- Join์ ํ ์ด๋ธ์ ์ํ ๋ฐฉํฅ์ผ๋ก ํฉ์น๋ค
ํ๋ก๊ทธ๋๋จธ์ค sql ๋ฌธ์ ์ค " ์คํ๋ผ์ธ/์จ๋ผ์ธ ํ๋งค ๋ฐ์ดํฐ ํตํฉํ๊ธฐ" ๋ฌธ์ ์์ Union์ ์ฌ์ฉํ๋ค.
ONLINE_SALE ํ ์ด๋ธ
OFFLINSE_SALE ํ ์ด๋ธ
ONLINE_SALE ํ ์ด๋ธ๊ณผ OFFLINE_SALE ํ ์ด๋ธ์์ 2022๋ 3์์ ์คํ๋ผ์ธ/์จ๋ผ์ธ ์ํ ํ๋งค ๋ฐ์ดํฐ๋ฅผ ์ถ์ถํ๋ ๋ฌธ์ ์๋ค. (OFFLINE_SALE ํ ์ด๋ธ์ USER_ID๊ฐ์ NULL ๋ก ํ์ํ๋ผ๋ ์กฐ๊ฑด์ด ์์๋ค.)
๋ ํ ์ด๋ธ์ ๊ฒฐ๊ณผ๋ฅผ ํฉ์น๊ธฐ ์ํด UNION์, ์คํ๋ผ์ธ ํ ์ด๋ธ์ USER_ID๋ฅผ NULL ๋ก ๋ํ๋ด๊ธฐ ์ํด NULL as user_id๋ฅผ ์ฌ์ฉํ๋ค.
(select date_format(sales_date,"%Y-%m-%d") as sales_date, product_id, user_id, sales_amount
from online_sale
where year(sales_date)=2022 and month(sales_date)=3
union
select date_format(sales_date,"%Y-%m-%d") as sales_date, product_id, NULL as user_id, sales_amount
from offline_sale
where year(sales_date)=2022 and month(sales_date)=3)
order by sales_date asc, product_id asc, user_id asc;
'๐๋ฐ์ดํฐ๋ฒ ์ด์ค:DB' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
SQLD (1) | 2024.01.14 |
---|---|
[MySQL] ์ต์์ ๋ ์ฝ๋ ํ๋ ๊ฐ์ ธ์ค๊ธฐ (0) | 2024.01.13 |
[MySQL] GROUP BY ... HAVING COUNT(*) (0) | 2024.01.05 |
[MySQL] not a GROUP BY expression (1) | 2024.01.04 |