๐Ÿ’ SQL/Group By

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค][SQL] ๋…ธ์„ ๋ณ„ ํ‰๊ท  ์—ญ ์‚ฌ์ด ๊ฑฐ๋ฆฌ ์กฐํšŒํ•˜๊ธฐ (284531)

์„ ๋‹ฌ 2024. 11. 1. 12:19
๋ฐ˜์‘ํ˜•

๋ฌธ์ œ

SUBWAY_DISTANCE ํ…Œ์ด๋ธ”์—์„œ ๋…ธ์„ ๋ณ„๋กœ ๋…ธ์„ , ์ด ๋ˆ„๊ณ„ ๊ฑฐ๋ฆฌ, ํ‰๊ท  ์—ญ ์‚ฌ์ด ๊ฑฐ๋ฆฌ๋ฅผ ๋…ธ์„ ๋ณ„๋กœ ์กฐํšŒํ•˜๋Š” SQL๋ฌธ์„ ์ž‘์„ฑํ•ด์ฃผ์„ธ์š”.

์ด ๋ˆ„๊ณ„๊ฑฐ๋ฆฌ๋Š” ํ…Œ์ด๋ธ” ๋‚ด ์กด์žฌํ•˜๋Š” ์—ญ๋“ค์˜ ์—ญ ์‚ฌ์ด ๊ฑฐ๋ฆฌ์˜ ์ด ํ•ฉ์„ ๋œปํ•ฉ๋‹ˆ๋‹ค.

 

์ด ๋ˆ„๊ณ„ ๊ฑฐ๋ฆฌ์™€ ํ‰๊ท  ์—ญ ์‚ฌ์ด ๊ฑฐ๋ฆฌ์˜ ์ปฌ๋Ÿผ๋ช…์€ ๊ฐ๊ฐ TOTAL_DISTANCE, AVERAGE_DISTANCE๋กœ ํ•ด์ฃผ์‹œ๊ณ ,

์ด ๋ˆ„๊ณ„๊ฑฐ๋ฆฌ๋Š” ์†Œ์ˆ˜ ๋‘˜์งธ์ž๋ฆฌ์—์„œ, ํ‰๊ท  ์—ญ ์‚ฌ์ด ๊ฑฐ๋ฆฌ๋Š” ์†Œ์ˆ˜ ์…‹์งธ ์ž๋ฆฌ์—์„œ ๋ฐ˜์˜ฌ๋ฆผ ํ•œ ๋’ค ๋‹จ์œ„(km)๋ฅผ ํ•จ๊ป˜ ์ถœ๋ ฅํ•ด์ฃผ์„ธ์š”.

 

๊ฒฐ๊ณผ๋Š” ์ด ๋ˆ„๊ณ„ ๊ฑฐ๋ฆฌ๋ฅผ ๊ธฐ์ค€์œผ๋กœ ๋‚ด๋ฆผ์ฐจ์ˆœ ์ •๋ ฌํ•ด์ฃผ์„ธ์š”.

 

ํ’€์ด

์ฃผ์˜ !!! concat์œผ๋กœ km๋ฅผ ๋ถ™์ด๋Š” ์ˆœ๊ฐ„ TOTLA_DISTANCE๋Š” ๋ฌธ์ž์—ด์ด ๋˜๊ธฐ ๋•Œ๋ฌธ์—

order by๊ฐ€ ์ ์šฉ๋˜์ง€ ์•Š๋Š”๋‹ค.

21.3km ์™€ 2.3km์„ ๋น„๊ตํ•˜๋ฉด 1.3์ด ๋” ํฌ๋‹ค๊ณ  ๋งํ•˜๋Š” ์ƒํ™ฉ ๋ฐœ์ƒ;;

concat(round(sum(D_BETWEEN_DIST), 1), 'km') as TOTAL_DISTANCE,

 

select ROUTE, 
    concat(round(sum(D_BETWEEN_DIST), 1), 'km') as TOTAL_DISTANCE, 
    concat(round(avg(D_BETWEEN_DIST), 2), 'km') as AVERAGE_DISTANCE
from SUBWAY_DISTANCE
group by ROUTE
order by sum(D_BETWEEN_DIST) desc
๋ฐ˜์‘ํ˜•