๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿ—‚.๋Œ€์™ธํ™œ๋™/๐Ÿ“.์นด์นด์˜คํด๋ผ์šฐ๋“œ์Šค์ฟจ

[DB] ๋ถ€์† ์งˆ์˜(sub query) ์—ฐ์Šต๋ฌธ์ œ

by ๐Ÿ’พ๊ณ ๊ตฌ๋งˆ๋ง›ํƒ•๋จน๊ณ ์‹ถ๋‹ค 2023. 12. 29.
728x90

1. ๋งˆ๋‹น์„œ์ ์˜ ๊ณ ๊ฐ์ด ์š”๊ตฌํ•˜๋Š” ๋‹ค์Œ ์งˆ๋ฌธ์— ๋Œ€ํ•ด SQL ๋ฌธ์„ ์ž‘์„ฑํ•˜์‹œ์˜ค.

  (5) ๋ฐ•์ง€์„ฑ์ด ๊ตฌ๋งคํ•œ ๋„์„œ์˜ ์ถœํŒ์‚ฌ ์ˆ˜

  (6) ๋ฐ•์ง€์„ฑ์ด ๊ตฌ๋งคํ•œ ๋„์„œ์˜ ์ด๋ฆ„, ๊ฐ€๊ฒฉ, ์ •๊ฐ€์™€ ํŒ๋งค๊ฐ€๊ฒฉ์˜ ์ฐจ์ด

  (7) ๋ฐ•์ง€์„ฑ์ด ๊ตฌ๋งคํ•˜์ง€ ์•Š์€ ๋„์„œ์˜ ์ด๋ฆ„

-- 5.
SELECT PUBLISHER
FROM BOOK
WHERE BOOKID IN (SELECT BOOKID
                 FROM ORDERS
                 WHERE CUSTID=1);

-- 6.
SELECT CS.NAME, BK.BOOKNAME, BK.PRICE, BK.PRICE - OD.SALEPRICE "์ฐจ์ด"
FROM CUSTOMER CS, ORDERS OD, BOOK BK
WHERE CS.CUSTID = OD.CUSTID AND
                OD.BOOKID = BK.BOOKID AND CS.CUSTID = 1;

-- 7.
SELECT BOOKNAME
FROM BOOK
MINUS
SELECT BOOKNAME
FROM BOOK
WHERE BOOKID IN (SELECT BOOKID
                 FROM ORDERS
                 WHERE CUSTID=1);

 

 

2. ๋งˆ๋‹น์„œ์ ์˜ ์šด์˜์ž์™€ ๊ฒฝ์˜์ž๊ฐ€ ์š”๊ตฌํ•˜๋Š” ๋‹ค์Œ ์งˆ๋ฌธ์— ๋Œ€ํ•ด SQL ๋ฌธ์„ ์ž‘์„ฑํ•˜์‹œ์˜ค.

  (8) ์ฃผ๋ฌธํ•˜์ง€ ์•Š์€ ๊ณ ๊ฐ์˜ ์ด๋ฆ„(๋ถ€์†์งˆ์˜ ์‚ฌ์šฉ)

  (9) ์ฃผ๋ฌธ ๊ธˆ์•ก์˜ ์ด์•ก๊ณผ ์ฃผ๋ฌธ์˜ ํ‰๊ท  ๊ธˆ์•ก

  (10) ๊ณ ๊ฐ์˜ ์ด๋ฆ„๊ณผ ๊ณ ๊ฐ๋ณ„ ๊ตฌ๋งค์•ก

  (11) ๊ณ ๊ฐ์˜ ์ด๋ฆ„๊ณผ ๊ณ ๊ฐ์ด ๊ตฌ๋งคํ•œ ๋„์„œ ๋ชฉ๋ก

  (12) ๋„์„œ์˜ ๊ฐ€๊ฒฉ(Book ํ…Œ์ด๋ธ”)๊ณผ ํŒ๋งค๊ฐ€๊ฒฉ(Orders ํ…Œ์ด๋ธ”)์˜ ์ฐจ์ด๊ฐ€ ๊ฐ€์žฅ ๋งŽ์€ ์ฃผ๋ฌธ

  (13) ๋„์„œ์˜ ํŒ๋งค์•ก ํ‰๊ท ๋ณด๋‹ค ์ž์‹ ์˜ ๊ตฌ๋งค์•ก ํ‰๊ท ์ด ๋” ๋†’์€ ๊ณ ๊ฐ์˜ ์ด๋ฆ„

-- 8.
SELECT NAME
FROM CUSTOMER
WHERE CUSTID NOT IN (SELECT CUSTID
                     FROM ORDERS);

-- 9.
SELECT SUM(SALEPRICE) "์ฃผ๋ฌธ์ด์•ก" ,  AVG(SALEPRICE) "์ฃผ๋ฌธํ‰๊ท "
FROM ORDERS;

-- 10.
SELECT CUSTID, NAME, (SELECT SUM(SALEPRICE)
                     FROM ORDERS OD
                     WHERE OD.CUSTID = CS.CUSTID) "๊ตฌ๋งค์•ก"
FROM CUSTOMER CS
GROUP BY CUSTID, NAME
ORDER BY CUSTID;

-- 11.
SELECT CS.NAME, BK.BOOKNAME
FROM CUSTOMER CS, ORDERS, BOOK BK
WHERE CS.CUSTID = ORDERS.CUSTID AND
                ORDERS.BOOKID = BK.BOOKID
ORDER BY NAME;

-- 12.
SELECT OD.ORDERID, MAX(BK.PRICE-OD.SALEPRICE) "ํฐ์ฐจ์ด"
FROM ORDERS OD, BOOK BK
WHERE OD.BOOKID = BK.BOOKID AND 
                BK.PRICE-OD.SALEPRICE = (SELECT MAX(BK.PRICE-OD.SALEPRICE)  
                                      FROM ORDERS OD , BOOK BK 
                                      WHERE OD.BOOKID = BK.BOOKID)
GROUP BY  OD.ORDERID;

-- 13.
SELECT CS.NAME, AVG(OD.SALEPRICE)
FROM CUSTOMER CS, ORDERS OD
WHERE CS.CUSTID = OD.CUSTID
GROUP BY CS.NAME
HAVING AVG(OD.SALEPRICE) > (SELECT AVG(SALEPRICE) FROM ORDERS);
728x90