๊ฐœ๋ฐœ์ผ์ง€

[MySQL] CASE WHEN / ์กฐ๊ฑด์— ๋ถ€ํ•ฉํ•˜๋Š” ์ค‘๊ณ ๊ฑฐ๋ž˜ ์ƒํƒœ ์กฐํšŒํ•˜๊ธฐ ๋ณธ๋ฌธ

SQL

[MySQL] CASE WHEN / ์กฐ๊ฑด์— ๋ถ€ํ•ฉํ•˜๋Š” ์ค‘๊ณ ๊ฑฐ๋ž˜ ์ƒํƒœ ์กฐํšŒํ•˜๊ธฐ

O'mil 2024. 5. 1. 15:31
728x90

๐Ÿ”— ๋งํฌ

์กฐ๊ฑด์— ๋ถ€ํ•ฉํ•˜๋Š” ์ค‘๊ณ ๊ฑฐ๋ž˜ ์ƒํƒœ ์กฐํšŒํ•˜๊ธฐ

 

๐Ÿ“Œ ๋ฌธ์ œ ์„ค๋ช…

Table: USED_GOODS_BOARD

  • 2022๋…„ 10์›” 5์ผ์— ๋“ฑ๋ก๋œ ์ค‘๊ณ ๊ฑฐ๋ž˜ ๊ฒŒ์‹œ๋ฌผ์˜ ๊ฒŒ์‹œ๊ธ€ ID, ์ž‘์„ฑ์ž ID, ๊ฒŒ์‹œ๊ธ€ ์ œ๋ชฉ, ๊ฐ€๊ฒฉ, ๊ฑฐ๋ž˜์ƒํƒœ๋ฅผ ์กฐํšŒ
    ๊ฑฐ๋ž˜์ƒํƒœ๊ฐ€ SALE์ด๋ฉด ํŒ๋งค์ค‘, RESERVED์ด๋ฉด ์˜ˆ์•ฝ์ค‘, DONE์ด๋ฉด ๊ฑฐ๋ž˜์™„๋ฃŒ ๋ถ„๋ฅ˜ํ•˜์—ฌ ์ถœ๋ ฅ
    ๊ฒฐ๊ณผ๋Š” ๊ฒŒ์‹œ๊ธ€ ID๋ฅผ ๊ธฐ์ค€์œผ๋กœ ๋‚ด๋ฆผ์ฐจ์ˆœ ์ •๋ ฌ

๐Ÿ’ป ์ฝ”๋“œ

SELECT BOARD_ID, WRITER_ID, TITLE, PRICE,
FROM USED_GOODS_BOARD
WHERE CREATED_DATE LIKE '2022-10-05'
ORDER BY BOARD_ID DESC;

 

 

๐Ÿ’ก ๊ฒฐ๊ณผ

 

 

โ“ ์˜๋ฌธ์ 

  • ๊ฑฐ๋ž˜์ƒํƒœ๋ฅผ ํŒ๋งค์ค‘, ์˜ˆ์•ฝ์ค‘, ๊ฑฐ๋ž˜์™„๋ฃŒ๋กœ ๋ถ„๋ฅ˜ํ•˜์—ฌ ์ถœ๋ ฅํ•˜๋Š” ๋ฒ•์„ ๋ชจ๋ฆ„..

 


๐Ÿ“ CASE  WHEN

  • ์ƒˆ๋กœ์šด ์—ด์„ ์ƒ์„ฑํ•˜๋Š” ๊ฒฝ์šฐ
  • ์—ด์„ ์ง‘๊ณ„ํ•˜๋Š” ๊ฒฝ์šฐ(์ง‘๊ณ„ํ•จ์ˆ˜์™€ ํ•จ๊ป˜ ์“ฐ์ž„
  • SELECT์ ˆ์—์„œ ์‚ฌ์šฉ
// ์ƒˆ๋กœ์šด ์—ด ์ƒ์„ฑ
SELECT
CASE
	WHEN ๊ธฐ์กด ์—ด = ์กฐ๊ฑด1 THEN '๊ฐ’1'
    WHEN ๊ธฐ์กด ์—ด = ์กฐ๊ฑด2 THEN '๊ฐ’2'
    WHEN ๊ธฐ์กด ์—ด = ์กฐ๊ฑด3 THEN '๊ฐ’3'
(ELSE์—ด) END AS ์ƒˆ๋กœ์šด ์—ด


// ์—ด ์ง‘๊ณ„
SELECT ์ง‘๊ณ„ํ•จ์ˆ˜((DISTINCT)
CASE
	WHEN ๊ธฐ์กด ์—ด = '์กฐ๊ฑด' THEN ์ง‘๊ณ„ ์—ด (ELSE๊ฐ’) END)
AS ์ƒˆ๋กœ์šด ์—ด

 

 

์˜ˆ์‹œ)

// ์ƒˆ๋กœ์šด ์—ด ์ƒ์„ฑ
// ์˜ˆ์‹œ1
SELECT *,
CASE
    WHEN `STATUS` = 'SALE' THEN 'ํŒ๋งค์ค‘'
    WHEN `STATUS` = 'RESERVED' THEN '์˜ˆ์•ฝ์ค‘'
    WHEN `STATUS` = 'DONE' THEN '๊ฑฐ๋ž˜์™„๋ฃŒ'
END AS `STATUS`
FROM EXAMPLE;

// ์˜ˆ์‹œ2
SELECT *,
CASE
	WHEN AGE BETWEEN 0 AND 7 THEN '์–ด๋ฆฐ์ด'
    WHEN AGE BETWEEN 8 AND 20 THEN '์ฒญ์†Œ๋…„'
    ELSE '์–ด๋ฅธ'
END AS '๋‚˜์ด ๋ถ„๋ฅ˜'
  • ์˜ˆ์‹œ2์—์„œ 'ELSE'๋ฌธ์„ ๋บ€๋‹ค๋ฉด ์–ด๋ฅธ์— ํ•ด๋‹นํ•œ๋Š” ๋‚˜์ด๋Š” ๋ชจ๋‘ NULL์ฒ˜๋ฆฌ๊ฐ€ ๋œ๋‹ค.

 


๐Ÿ’ป ์ฝ”๋“œ

SELECT BOARD_ID, WRITER_ID, TITLE, PRICE,
CASE
    WHEN `STATUS` = 'SALE' THEN 'ํŒ๋งค์ค‘'
    WHEN `STATUS` = 'RESERVED' THEN '์˜ˆ์•ฝ์ค‘'
    WHEN `STATUS` = 'DONE' THEN '๊ฑฐ๋ž˜์™„๋ฃŒ'
END AS `STATUS`
FROM USED_GOODS_BOARD
WHERE CREATED_DATE LIKE '2022-10-05'
ORDER BY BOARD_ID DESC;

 

 

 

๐Ÿ’ก ๊ฒฐ๊ณผ

 


๐Ÿ“šReference

https://suy379.tistory.com/110

 

 

 

728x90
Comments