πŸ’» [SQL] 4. μˆœμœ„ ν•¨μˆ˜(RANK Function)

thisk336Β·2023λ…„ 10μ›” 4일
0

SQL

λͺ©λ‘ 보기
4/17
post-thumbnail

μˆœμœ„ ν•¨μˆ˜

  • μœˆλ„μš° ν•¨μˆ˜μ—μ„œλŠ” νŠΉμ • ν•­λͺ©κ³Ό νŒŒν‹°μ…˜μ— λŒ€ν•΄μ„œ μˆœμœ„λ₯Ό 계산할 수 μžˆλŠ” ν•¨μˆ˜λ₯Ό μ œκ³΅ν•œλ‹€.
  • μˆœμœ„ ν•¨μˆ˜λŠ” RANK, DENSE_RANK, ROW_NUMBER ν•¨μˆ˜κ°€ μžˆλ‹€.

RANK ν•¨μˆ˜

  • RANK ν•¨μˆ˜λŠ” νŠΉμ •ν•­λͺ© 및 νŒŒν‹°μ…˜μ— λŒ€ν•΄μ„œ μˆœμœ„λ₯Ό κ³„μ‚°ν•˜λŠ” ν•¨μˆ˜λ‘œ λ™μΌν•œ μˆœμœ„λŠ” λ™μΌν•œ 값이 λΆ€μ—¬λœλ‹€.

  • κΈ°λ³Έ κ΅¬μ‘°λŠ” λ‹€μŒκ³Ό κ°™λ‹€.

SELECT [컬럼λͺ…],
RANK() OVER (ORDER BY [컬럼λͺ…] ASC/DESC)
FROM [ν…Œμ΄λΈ”λͺ…]
WHERE [쑰건식];
  • 기본적으둜 μ˜€λ¦„μ°¨μˆœμœΌλ‘œ μˆœμœ„λ₯Ό 보여주며, DESC둜 μ„€μ •ν•˜λ©΄ λ‚΄λ¦Όμ°¨μˆœμœΌλ‘œ μˆœμœ„λ₯Ό 보여쀀닀.
INSERT INTO mytable
(name, model_num, model_type, lowest_price)
VALUES('i3', '13700KF', 'μ—˜λ”λ ˆμ΄ν¬', 287240);

SELECT model_num, lowest_price,
RANK() OVER (ORDER BY lowest_price ASC) AS price_rank
FROM mytable
WHERE lowest_price BETWEEN 200000 AND 500000;

DENSE_RANK ν•¨μˆ˜

  • DENSE_RANK ν•¨μˆ˜λŠ” RANK ν•¨μˆ˜μ™€ λ§ˆμ°¬κ°€μ§€λ‘œ νŠΉμ •ν•­λͺ© 및 νŒŒν‹°μ…˜μ— λŒ€ν•΄μ„œ μˆœμœ„λ₯Ό κ³„μ‚°ν•˜λŠ” ν•¨μˆ˜μ΄λ‚˜ RANK ν•¨μˆ˜μ™€ λ‹€λ₯΄κ²Œ λ™μΌν•œ μˆœμœ„λ₯Ό ν•˜λ‚˜μ˜ 건수둜 κ³„μ‚°ν•œλ‹€.

  • κΈ°λ³Έ κ΅¬μ‘°λŠ” λ‹€μŒκ³Ό κ°™λ‹€.

SELECT [컬럼λͺ…],
DENSE_RANK() OVER (ORDER BY [컬럼λͺ…] ASC/DESC)
FROM [ν…Œμ΄λΈ”λͺ…]
WHERE [쑰건식];
SELECT model_num, lowest_price,
DENSE_RANK() OVER (ORDER BY lowest_price ASC) AS price_rank
FROM mytable
WHERE lowest_price BETWEEN 200000 AND 500000;


μœ„ κ·Έλ¦Όμ—μ„œ 같이 RANK ν•¨μˆ˜μ™€ λ‹€λ₯΄κ²Œ 325,760μ›μ˜ 데이터가 4μœ„μ—μ„œ 3μœ„λ‘œ 바뀐것을 μ•Œ 수 μžˆλ‹€. μ΄λŠ” 2μœ„μΈ 287,240μ›μ˜ 데이터λ₯Ό 두 개의 κ±΄μˆ˜κ°€ μ•„λ‹Œ ν•˜λ‚˜μ˜ 건수둜 κ³„μ‚°ν–ˆκΈ° λ•Œλ¬Έμ΄λ‹€.

ROW_NUMBER ν•¨μˆ˜

  • ROW_NUMBER ν•¨μˆ˜λŠ” νŠΉμ •ν•­λͺ©μ— λŒ€ν•΄μ„œ μˆœμœ„λ₯Ό κ³„μ‚°ν•œ ν›„ λ™μΌν•œ μˆœμœ„μ— λŒ€ν•΄μ„œ 고유의 μˆœμœ„λ₯Ό λΆ€μ—¬ν•œλ‹€.

  • κΈ°λ³Έ κ΅¬μ‘°λŠ” λ‹€μŒκ³Ό κ°™λ‹€.

SELECT [컬럼λͺ…],
ROW_NUMBER() OVER (ORDER BY [컬럼λͺ…] ASC/DESC)
FROM [ν…Œμ΄λΈ”λͺ…]
WHERE [쑰건식];
SELECT model_num, lowest_price,
ROW_NUMBER() OVER (ORDER BY lowest_price ASC) AS price_rank
FROM mytable
WHERE lowest_price BETWEEN 200000 AND 500000;

  • μ„Έ ν•¨μˆ˜λ₯Ό λ™μ‹œμ— λΉ„κ΅ν•˜λ©΄ λ‹€μŒκ³Ό κ°™λ‹€.
SELECT model_num, lowest_price,
RANK() OVER (ORDER BY lowest_price ASC) AS price_rank,
DENSE_RANK() OVER (ORDER BY lowest_price ASC) AS price_dense_rank,
ROW_NUMBER() OVER (ORDER BY lowest_price ASC) AS price_row_number
FROM mytable
WHERE lowest_price BETWEEN 200000 AND 500000;

0개의 λŒ“κΈ€