๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค/์•Œ๊ณ ๋ฆฌ์ฆ˜ ํ’€์ด(SQL)

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค_์นดํ…Œ๊ณ ๋ฆฌ ๋ณ„ ๋„์„œ ํŒ๋งค๋Ÿ‰ ์ง‘๊ณ„ํ•˜๊ธฐ

by carrot0911 2024. 11. 19.

๋ฌธ์ œ ์„ค๋ช…

https://school.programmers.co.kr/learn/courses/30/lessons/144855

 

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

SW๊ฐœ๋ฐœ์ž๋ฅผ ์œ„ํ•œ ํ‰๊ฐ€, ๊ต์œก, ์ฑ„์šฉ๊นŒ์ง€ Total Solution์„ ์ œ๊ณตํ•˜๋Š” ๊ฐœ๋ฐœ์ž ์„ฑ์žฅ์„ ์œ„ํ•œ ๋ฒ ์ด์Šค์บ ํ”„

programmers.co.kr

๋‹ค์Œ์€ ์–ด๋Š ํ•œ ์„œ์ ์—์„œ ํŒ๋งค์ค‘์ธ ๋„์„œ๋“ค์˜ ๋„์„œ ์ •๋ณด(BOOK), ํŒ๋งค ์ •๋ณด(BOOK_SALES) ํ…Œ์ด๋ธ”์ž…๋‹ˆ๋‹ค.
BOOK
 ํ…Œ์ด๋ธ”์€ ๊ฐ ๋„์„œ์˜ ์ •๋ณด๋ฅผ ๋‹ด์€ ํ…Œ์ด๋ธ”๋กœ ์•„๋ž˜์™€ ๊ฐ™์€ ๊ตฌ์กฐ๋กœ ๋˜์–ด์žˆ์Šต๋‹ˆ๋‹ค.

Column name Type Nullable Description
BOOK_ID INTEGER FALSE ๋„์„œ ID
CATEGORY VARCHAR(N) FALSE ์นดํ…Œ๊ณ ๋ฆฌ
(๊ฒฝ์ œ, ์ธ๋ฌธ, ์†Œ์„ค, ์ƒํ™ฉ, ๊ธฐ์ˆ )
AUTHOR_ID INTEGER FALSE ์ €์ž ID
PRICE INTEGER FALSE ํŒ๋งค๊ฐ€ (์›)
PUBLISHED_DATE DATE FALSE ์ถœํŒ์ผ

BOOK_SALES ํ…Œ์ด๋ธ”์€ ๊ฐ ๋„์„œ์˜ ๋‚ ์งœ ๋ณ„ ํŒ๋งค๋Ÿ‰ ์ •๋ณด๋ฅผ ๋‹ด์€ ํ…Œ์ด๋ธ”๋กœ ์•„๋ž˜์™€ ๊ฐ™์€ ๊ตฌ์กฐ๋กœ ๋˜์–ด์žˆ์Šต๋‹ˆ๋‹ค.

Column name Type Nullable Description
BOOK_ID INTEGER FALSE ๋„์„œ ID
SALES_DATE DATE FALSE ํŒ๋งค์ผ
SALES INTEGER FALSE ํŒ๋งค๋Ÿ‰


๋ฌธ์ œ

2022๋…„ 1์›”์˜ ์นดํ…Œ๊ณ ๋ฆฌ ๋ณ„ ๋„์„œ ํŒ๋งค๋Ÿ‰์„ ํ•ฉ์‚ฐํ•˜๊ณ , ์นดํ…Œ๊ณ ๋ฆฌ(CATEGORY), ์ด ํŒ๋งค๋Ÿ‰(TOTAL_SALES) ๋ฆฌ์ŠคํŠธ๋ฅผ ์ถœ๋ ฅํ•˜๋Š” SQL๋ฌธ์„ ์ž‘์„ฑํ•ด์ฃผ์„ธ์š”.
๊ฒฐ๊ณผ๋Š” ์นดํ…Œ๊ณ ๋ฆฌ๋ช…์„ ๊ธฐ์ค€์œผ๋กœ ์˜ค๋ฆ„์ฐจ์ˆœ ์ •๋ ฌํ•ด์ฃผ์„ธ์š”.

์˜ˆ์‹œ

์˜ˆ๋ฅผ ๋“ค์–ด BOOK ํ…Œ์ด๋ธ”๊ณผ BOOK_SALES ํ…Œ์ด๋ธ”์ด ๋‹ค์Œ๊ณผ ๊ฐ™๋‹ค๋ฉด

BOOK_ID CATEGORY AUTHOR_ID PRICE PUBLISHED
_DATE
1 ์ธ๋ฌธ 1 10000 2020-01-01
2 ๊ฒฝ์ œ 1 9000 2021-02-05
3 ๊ฒฝ์ œ 2 9000 2021-03-11
BOOK_ID SALES_DATE SALES
1 2022-01-01 2
2 2022-01-02 3
1 2022-01-05 1
2 2022-01-20 5
2 2022-01-21 6
3 2022-01-22 2
2 2022-02-11 3

 

๋‚ด๊ฐ€ ์ž‘์„ฑํ•œ ์ฝ”๋“œ

SELECT B.CATEGORY, SUM(BS.SALES) AS TOTAL_SALES
FROM BOOK B LEFT JOIN BOOK_SALES BS
ON B.BOOK_ID=BS.BOOK_ID
WHERE BS.SALES_DATE BETWEEN '2022-01-01' AND '2022-01-31'
GROUP BY B.CATEGORY
ORDER BY B.CATEGORY;

์ฝ”๋“œ ์„ค๋ช…

  • SELECT B.CATEGORY, SUM(BS.SALES) AS TOTAL_SALES : BOOK ํ…Œ์ด๋ธ”์˜ CATEGORY ์ปฌ๋Ÿผ๊ณผ BOOK_SALES ํ…Œ์ด๋ธ”์˜ SALES ์ปฌ๋Ÿผ์˜ ํ•ฉ๊ณ„๋ฅผ TOTAL_SALES๋ผ๊ณ  ์ง€์ •ํ•˜๊ณ  ์„ ํƒํ•œ๋‹ค.
  • FROM BOOK B LEFT JOIN BOOK_SALES BS : BOOK ํ…Œ์ด๋ธ”์„ B, BOOK_SALES๋ฅผ BS๋กœ ์ง€์ •ํ•œ ํ›„ LEFT JOIN์„ ํ†ตํ•ด ๋ฐ์ดํ„ฐ๋ฅผ ํ•ฉ์นœ๋‹ค.
  • ON B.BOOK_ID = BS.BOOK_ID : BOOK ํ…Œ์ด๋ธ”์˜ BOOK_ID์™€ BOOK_SALES์˜ BOOK_ID๊ฐ€ ๊ฐ™์€ ๋ฐ์ดํ„ฐ๋งŒ LEFT JOIN์„ ์ง„ํ–‰ํ•˜๋„๋ก ์กฐ๊ฑด์„ ๊ฑธ์–ด์ค€๋‹ค.
  • WHERE BS.SALES_DATE BETWEEN '2022-01-01' AND '2022-01-31' : BOOK_SALES ํ…Œ์ด๋ธ”์˜ SALES_DATE ์ปฌ๋Ÿผ์˜ ๋ฐ์ดํ„ฐ๊ฐ€ ๊ฐ’์ด '2022-01-01'์™€ '2022-01-31' ์‚ฌ์ด์˜ ๊ฐ’๋งŒ ๊ฐ€์ ธ์˜จ๋‹ค.
  • GROUP BY B.CATEGORY : BOOK ํ…Œ์ด๋ธ”์˜ CATEGORY ์ปฌ๋Ÿผ์„ ๊ธฐ์ค€์œผ๋กœ ๊ทธ๋ฃนํ™”ํ•œ๋‹ค.
  • ORDER BY B.CATEGORY : BOOK ํ…Œ์ด๋ธ”์˜ CATEGORY ์ปฌ๋Ÿผ์„ ๊ธฐ์ค€์œผ๋กœ ์˜ค๋ฆ„์ฐจ์ˆœ ์ •๋ ฌํ•œ๋‹ค.