๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

SQL

[SQL] MySQL - ORDER BY ์™€ IN ํ•จ๊ป˜ ์‚ฌ์šฉํ•˜๊ธฐ

๋ฐ˜์‘ํ˜•

๐Ÿ”Š ๋ณธ ํฌ์ŠคํŒ…์—์„œ ์‚ฌ์šฉ๋˜๋Š” ํ…Œ์ด๋ธ”์˜ ์ž๋ฃŒ์™€ ์ถœ์ฒ˜๋Š” SQL Zoo์ž„์„ ๋ฐํž™๋‹ˆ๋‹ค. ๋” ๋‹ค์–‘ํ•œ SQL ๋ฌธ์ œ๋ฅผ ํ’€์–ด๋ณด์‹œ๋ ค๋ฉด SQL Zoo ์‚ฌ์ดํŠธ๋ฅผ ๋ฐฉ๋ฌธํ•ด๋ณด์„ธ์š”!

 

SQL ๋ฌธ์ œ ํ’€์ด ์‚ฌ์ดํŠธ์ธ SQL Zoo

 

์ด๋ฒˆ ํฌ์ŠคํŒ…์—์„œ๋Š” ORDER BY ์ ˆ์— IN ๋ฌธ๋ฒ•์„ ์‚ฌ์šฉํ•˜๋Š” ๋ฐฉ๋ฒ•์œผ๋กœ SQL ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ•˜๋Š” ๋ฐฉ๋ฒ•์— ๋Œ€ํ•ด ์•Œ์•„๋ณด๋ ค๊ณ  ํ•œ๋‹ค. ํ•ด๋‹น ๋ฌธ์ œ๋Š” ์—ฌ๊ธฐ์˜ 14๋ฒˆ ๋ฌธ์ œ์ด๋‹ค.

 

์šฐ์„  ๋ฌธ์ œ๋ฅผ ํ’€๊ธฐ ์œ„ํ•ด ์‚ฌ์šฉ๋˜๋Š” ํ…Œ์ด๋ธ”๊ณผ ๋ฌธ์ œ๋ฅผ ์‚ดํŽด๋ณด์ž.

 

๋…ธ๋ฒจ ์ˆ˜์ƒ์ž ๊ด€๋ จ ํ…Œ์ด๋ธ”

 

Show the 1984 winners and subject ordered by subject and winner name; but list Chemistry and Physics last.
(1984๋…„์— ์ˆ˜์ƒํ•œ ์ˆ˜์ƒ์ž๋“ค์„ ์ถœ๋ ฅํ•˜๋Š”๋ฐ ์šฐ์„  subject ๊ธฐ์ค€์œผ๋กœ ์˜ค๋ฆ„์ฐจ์ˆœ(์•ŒํŒŒ๋ฒณ ์ˆœ์„œ)๋กœ ์ •๋ ฌํ•œ ํ›„  winner ๊ธฐ์ค€์œผ๋กœ ์˜ค๋ฆ„์ฐจ์ˆœ์œผ๋กœ ์ •๋ ฌํ•ด๋ผ. ์ด ๋•Œ subject์—์„œ 'Chemistry' ์™€ 'Physics' ๊ฐ’์ด ๋“ค์–ด์žˆ๋Š” ๋ฐ์ดํ„ฐ๋Š” ๊ฐ€์žฅ ๋’ค๋กœ ์ •๋ ฌ์‹œ์ผœ๋ผ.)

 

์ž, ์ด์ œ ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ•˜๊ธฐ ์œ„ํ•ด ํ•˜๋‚˜์”ฉ ์กฐ๊ฑด์„ ๋งž์ถฐ๋ณด์ž. 

 

  1. ์šฐ์„ , 1984๋…„์— ์ˆ˜์ƒํ•œ ์ˆ˜์ƒ์ž๋“ค์„ WHERE ์กฐ๊ฑด์œผ๋กœ ํ•„ํ„ฐ๋ง
  2. subject๊ฐ€ 'Chemistry', 'Physics' ์ธ ๋ฐ์ดํ„ฐ๋“ค์„ ๊ฐ€์žฅ ๋’ค๋กœ ์ •๋ ฌ
  3. 2๋ฒˆ ์ •๋ ฌ ๊ธฐ์ค€ ์„ค์ • ์ดํ›„, subject โžก๏ธ winner ์ˆœ์œผ๋กœ ์˜ค๋ฆ„์ฐจ์ˆœ ์ •๋ ฌ

์ด ๋•Œ, 2๋ฒˆ์งธ ์ •๋ ฌ ์กฐ๊ฑด์„ ์‹คํ–‰ํ•˜๊ธฐ ์œ„ํ•ด ORDER BY์— IN์„ ์‚ฌ์šฉํ•˜์—ฌ ์‰ฝ๊ฒŒ ๊ตฌํ˜„ํ•  ์ˆ˜ ์žˆ๋‹ค.

 

ORDER BY subject IN ('Chemisty', 'Physics') [ASC | DESC]

 

์œ„ ๊ตฌ๋ฌธ์„ ์ง๊ด€์ ์œผ๋กœ ํ•ด์„ํ•ด๋ณด์ž๋ฉด "subject ๊ฐ’ ์ค‘์— 'Chemistry' ๋˜๋Š” 'Physics' ๊ฐ€ ๋“ค์–ด์žˆ๋Š” ๋ฐ์ดํ„ฐ๋“ค์„ ASC(์˜ค๋ฆ„์ฐจ์ˆœ) ๋˜๋Š” DESC(๋‚ด๋ฆผ์ฐจ์ˆœ)์œผ๋กœ ์ •๋ ฌํ•ด๋ผ!" ์—ฌ๊ธฐ์„œ ASC ๋ผ๊ณ  ์„ค์ •ํ•˜๊ฒŒ ๋˜๋ฉด ํ…Œ์ด๋ธ”์˜ ๊ฐ€์žฅ ์ƒ๋‹จ์—, DESC ๋ผ๊ณ  ์„ค์ •ํ•˜๋ฉด ํ…Œ์ด๋ธ”์˜ ๊ฐ€์žฅ ํ•˜๋‹จ์— ์ถœ๋ ฅ๋˜๋Š” ๊ฒƒ์„ ๋ณผ ์ˆ˜ ์žˆ๋‹ค. ์ด์ œ ํ•ด๋‹น ๋ฌธ์ œ์˜ ์ •๋‹ต์ธ ์ „์ฒด SQL ๊ตฌ๋ฌธ์„ ์ž‘์„ฑํ•˜๋ฉด ๋‹ค์Œ๊ณผ ๊ฐ™๋‹ค.(์ฐธ๊ณ ๋กœ ASC/DESC ์ค‘ ์•„๋ฌด๊ฒƒ๋„ ์ž…๋ ฅํ•ด์ฃผ์ง€ ์•Š์œผ๋ฉด ์ •๋ ฌ ๋””ํดํŠธ ๊ฐ’์œผ๋กœ ASC ๊ฐ€ ์ž๋™์„ค์ • ๋œ๋‹ค.) 

 

SELECT winner, subject
FROM nobel
WHERE yr = 1984
ORDER BY subject IN ('Chemistry', 'Physics'), subject, winner

 

 

๋ฐ˜์‘ํ˜•