[SQL] group by, order by, Alias

CountryGirlΒ·2023λ…„ 6μ›” 3일
0

SQL

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

πŸ“Œ group by

λ™μΌν•œ λ²”μ£Όμ˜ 데이터λ₯Ό ν•˜λ‚˜λ‘œ λ¬Άμ–΄μ„œ, 범주별 톡계λ₯Ό λ‚΄μ€€λ‹€.

select ν•„λ“œλͺ…, count(ν•„λ“œλͺ…) from ν…Œμ΄λΈ”λͺ…		// λ™μΌν•œ ν•„λ“œκ°’μ„ 그룹으둜 λ¬Άμ–΄μ„œ κ·Έλ£Ήλ³„λ‘œ λͺ‡ κ°œμΈμ§€ μ•Œλ €μ€˜
group by ν•„λ“œλͺ…

쿼리가 μ§„ν–‰λ˜λŠ” μˆœμ„œ: from ➜ group by ➜ select


πŸ“Œ order by

κΉ”λ”ν•˜κ²Œ μ •λ ¬ν•˜κΈ°

  • κΈ°λ³Έκ°’μœΌλ‘œ μ˜€λ¦„μ°¨μˆœ
select ν•„λ“œλͺ… from ν…Œμ΄λΈ”λͺ…		
order by ν•„λ“œλͺ…				// μ˜€λ¦„μ°¨μˆœμœΌλ‘œ μ •λ ¬ν•΄μ€˜

select ν•„λ“œλͺ… from ν…Œμ΄λΈ”λͺ…		
order by ν•„λ“œλͺ… desc			// λ‚΄λ¦Όμ°¨μˆœμœΌλ‘œ μ •λ ¬ν•΄μ€˜

쿼리가 μ§„ν–‰λ˜λŠ” μˆœμ„œ: from ➜ select ➜ order by


πŸ“Œ 톡계

πŸ€” μ΅œλŒ€

ν•„λ“œκ°’ 쀑에 κ°€μž₯ 큰 값을 μ•Œλ €μ€€λ‹€.

select  max(ν•„λ“œλͺ…) from ν…Œμ΄λΈ”λͺ…
group by ν•„λ“œλͺ…

πŸ€” μ΅œμ†Œ

ν•„λ“œκ°’ 쀑에 κ°€μž₯ μž‘μ€ 값을 μ•Œλ €μ€€λ‹€.

select  min(ν•„λ“œλͺ…) from ν…Œμ΄λΈ”λͺ…
group by ν•„λ“œλͺ…

πŸ€” 합계

λͺ¨λ“  ν•„λ“œκ°’μ„ λ”ν•œ 합계λ₯Ό μ•Œλ €μ€€λ‹€.

select  sum(ν•„λ“œλͺ…) from ν…Œμ΄λΈ”λͺ…
group by ν•„λ“œλͺ…

πŸ€” 평균

ν•„λ“œκ°’μ˜ 평균 μ•Œλ €μ€€λ‹€.

select  avg(ν•„λ“œλͺ…) from ν…Œμ΄λΈ”λͺ…
group by ν•„λ“œλͺ…

πŸ€” 반올림

ν•„λ“œκ°’μ˜ 평균이 μ†Œμˆ˜λ‘œ λ‚˜μ˜¬ λ•Œ λ°˜μ˜¬λ¦Όμ„ ν•΄μ€€λ‹€

select  round(ν•„λ“œλͺ…, λͺ‡ 번째 μžλ¦¬κΉŒμ§€) from ν…Œμ΄λΈ”λͺ…
group by ν•„λ“œλͺ…

πŸ“Œ Alias

쿼리가 점점 κΈΈμ–΄μ§€λ©΄μ„œ ν—·κ°ˆλ¦¬λŠ” 일이 생길 수 μžˆμ–΄μ„œ μ•½μžμ²˜λŸΌ AliasλΌλŠ” 별칭 κΈ°λŠ₯이 μžˆλ‹€.
ν…Œμ΄λΈ”λͺ… 뒀에 별칭을 써주고 μ‚¬μš©ν•  λ•ŒλŠ” 별칭. 으둜 μ‚¬μš©ν•  수 μžˆλ‹€.

select ν•„λ“œλͺ… from ν…Œμ΄λΈ”λͺ… 별칭
where 별칭.ν•„λ“œλͺ… = '****'

---------------------------------

select aa from A_table A
where A.number = '****'

πŸ€” as

뒀에 asλ₯Ό λΆ™μ—¬μ„œ 별칭을 μΆ”κ°€ν•  μˆ˜λ„ μžˆλ‹€.

select ν•„λ“œλͺ… as ν•„λ“œλͺ…A from ν…Œμ΄λΈ”λͺ…

---------------------------------

select count(*) as cnt from A_table 
profile
πŸ’»πŸŒΎμ‹œκ³¨μ†Œλ…€μ˜ 엉망징창 개발 μ„±μž₯μΌμ§€πŸŒΎπŸ’» (2023.05.23 ~)

0개의 λŒ“κΈ€