๊ด€๋ฆฌ ๋ฉ”๋‰ด

JiYoung Dev ๐Ÿ–ฅ

[database ๊ณ ๊ธ‰] ์œˆ๋„์šฐ ํ•จ์ˆ˜ (2023.08.09) ๋ณธ๋ฌธ

full stack/database

[database ๊ณ ๊ธ‰] ์œˆ๋„์šฐ ํ•จ์ˆ˜ (2023.08.09)

Shinjio 2023. 8. 9. 15:25

 

 

SELECT PRD_ID
     , PRD_NAME
     , PRD_AMT
     , DENSE_RANK() OVER (ORDER BY PRD_AMT DESC) AS ๊ฐ€๊ฒฉ๋Œ€์ˆœ์œ„
  FROM TB_PRD;

 

์œˆ๋„์šฐํ•จ์ˆ˜ : ํ…Œ์ด๋ธ”์˜ ํ–‰๊ณผ ํ–‰๊ฐ„์˜ ๊ด€๊ณ„๋ฅผ ์ด์šฉํ•ด์„œ ์˜๋ฏธ์žˆ๋Š” ๋ฐ์ดํ„ฐ๋ฅผ ๋ฝ‘๋Š”๋‹ค. 

 

  • RANK : ์ค‘๋ณต๋œ ์ˆœ์œ„ ๋‹ค์Œ ์ˆซ์ž ๊ฑด๋„ˆ๋œ€
  • DENSE_RANK : ์ค‘๋ณต๋œ ์ˆœ์œ„ ๋‹ค์Œ ์ˆซ์ž ๊ฑด๋„ˆ๋›ฐ์ง€ ์•Š์Œ
  • ROW_NUMBER : ๊ณ ์œ ํ•œ ์ˆซ์ž

 

 

์‹คํ–‰์ˆœ์„œ

 

 

 

์ธ๋ผ์ธ๋ทฐ๋ฅผ ์ด์šฉํ•ด์„œ ์กฐ๊ฑด ๋ถ€์—ฌ ๊ฐ€๋Šฅ

 

SELECT *
    FROM (
            SELECT PRD_ID
                 , PRD_NAME
                 , PRD_AMT
                 , DENSE_RANK() OVER (ORDER BY PRD_AMT DESC) AS ๊ฐ€๊ฒฉ๋Œ€์ˆœ์œ„
              FROM TB_PRD
        )
 WHERE ๊ฐ€๊ฒฉ๋Œ€์ˆœ์œ„ <= 5;

 

 

์ž„์‹œ ํ…Œ์ด๋ธ” ์ƒ์„ฑ : WITH - AS

์ธ๋ผ์ธ๋ทฐ๊ฐ€ ๋„ˆ๋ฌด ๊ธธ์–ด์ง€๋ฉด WITH๋กœ ์„ ์–ธ ํ›„ SELECT ์—์„œ ํ™œ์šฉ

 

PARTITION BY

 

SELECT ๊ฒฝ๊ธฐ์žฅ , ์Šน์ž , ํŒจ์ž , ์ ์ˆ˜์ฐจ
 , ROW_NUMBER() OVER ( PARTITION BY ๊ฒฝ๊ธฐ์žฅ ORDER BY ์ ์ˆ˜์ฐจ DESC ) AS 
RNUM 
FROM ์›”๋“œ์ปต๊ฒฝ๊ธฐ๋‚ด์—ญ

 

 

 

๊ทธ๋ฃน๋ณ„ 1๋“ฑ๊ณผ ๊ฐ™์€ ์กฐ๊ฑด ๋ถ€์—ฌํ•  ๋•Œ ROW_NUMBER, PARTITION BY์™€ ํ•จ๊ป˜ ๋งŽ์ด ์‚ฌ์šฉ

 

GROUP BY๋Š” ์‹ค์ œ๋กœ ํ–‰์ด ์ค„์–ด๋ฒ„๋ฆฐ๋‹ค. 

PARTITION BY๋Š” ํ–‰์ด ์ค„์ง€ ์•Š๋Š”๋‹ค. (์›๋ณธ ๊ทธ๋Œ€๋กœ ์œ ์ง€) 

 

 

SELECT ๊ฒฝ๊ธฐ์žฅ , ์Šน์ž , ํŒจ์ž , ์ ์ˆ˜์ฐจ
 FROM ( 
        SELECT ๊ฒฝ๊ธฐ์žฅ , ์Šน์ž , ํŒจ์ž , ์ ์ˆ˜์ฐจ
         , ROW_NUMBER() OVER ( PARTITION BY ๊ฒฝ๊ธฐ์žฅ ORDER BY ์ ์ˆ˜์ฐจ DESC ) AS 
        RNUM 
        FROM ์›”๋“œ์ปต๊ฒฝ๊ธฐ๋‚ด์—ญ
         ) 
WHERE RNUM = 1;

 

LEAD, LEG 

 

  • LEG : ํ˜„์žฌ ๋ฐ์ดํ„ฐ ๊ธฐ์ค€ ์ด์ „ ๋ฐ์ดํ„ฐ ๊ฐ€์ ธ์˜ฌ ๋•Œ
  • LEAD : ํ˜„์žฌ ๋ฐ์ดํ„ฐ ๊ธฐ์ค€ ์ดํ›„ ๋ฐ์ดํ„ฐ ๊ฐ€์ ธ์˜ฌ ๋•Œ

 

(์ข…๊ฐ€, 1, 0)

์ข…๊ฐ€ : ๊ธฐ์ค€

1 : 1๊ฐœ ์ด์ „ ํ˜น์€ ์ดํ›„ 

0 : DEFAULT 

 

SELECT ์ข…๋ชฉ
 , ์ผ์ž
 , ์ข…๊ฐ€
 , LAG(์ข…๊ฐ€ ,1, 0) OVER(ORDER BY ์ผ์ž) AS ์ „๋‚ ๋Œ€๋น„์ข…๊ฐ€์ฐจ์ด
 , ์ข…๊ฐ€ - LAG(์ข…๊ฐ€ ,1, 0) OVER(ORDER BY ์ผ์ž) AS ์ „๋‚ ๋Œ€๋น„์ข…๊ฐ€์ฐจ์ด
 FROM STOCK 
;