sql κΈ°μ΄ + group by / order by / where μ€λ³΅
limit μ«μ
π ν μ΄λΈμμ λ°μ΄ν° 'μ«μ' κ°μ λ§νΌλ§ μλΌμ 보μ¬μ€.
select * from checkins
limit 5
max(νλλͺ ) / min(νλλͺ )
π μ΅λκ° κ΅¬νκΈ° / μ΅μκ° κ΅¬νκΈ°.
select week, min(likes) from checkins
group by week
avg(νλλͺ )
π νκ· κ΅¬νκΈ°.
select week,avg(likes) from checkins
group by week
round( , μ«μ)
π μμ«μ "μ«μ" μ리 κΉμ§λ§ λμ€κ² λ°μ¬λ¦Ό ν΄μ€
μ ) round κ΄νΈ λμ μ ν μ«μκ° 2λΌλ©΄, μμ«μ 2μ§Έ μ리 κΉμ§λ§ λμ€κ² ν΄μ€.
select week, round(avg(likes),3) from checkins
group by week
count(νλλͺ )
π ν΄λΉ νλμ κ°μ ꡬνκΈ°. *λ‘ νλ©΄ μ 체 κ°μ ꡬνλ κ².
π countλ NULLμ μΈμ§ μλλ€
select week, count(likes) from checkins
group by week
sum(νλλͺ )
π νλ μμ λ°μ΄ν°λ€ λ€ λν΄μ€. ν©κ³ ꡬνκΈ°.
select week, sum(likes) from checkins
group by week
group by νλμ΄λ¦
π λμΌ νλ λ΄μ λ°μ΄ν°λ₯Ό νλλ‘ λ¬Άμ μ μμ.
name νλμ λ°μ΄ν°κ° μ΄** κΉ** μμΌλ‘ μ μ₯λμ΄ μλ€λ©΄, group byλ₯Ό ν΅ν΄ κ°μ nameμ κ°λ λ°μ΄ν°λ₯Ό ν©μΉ¨.
select * from users u
group by name
order by νλμ΄λ¦
π λ°μ΄ν° μ λ ¬νκ³ μ ν λ μ. λν΄νΈλ μ€λ¦μ°¨μ. asc
π λ΄λ¦Όμ°¨μ desc
π μ«μ, λ¬Έμμ΄, μκ°λ μ λ ¬μ΄ κ°λ₯ν¨
select name, count(*) from users
group by name
order by count(*)desc
μ λ ¬μ μΈμ λ λ§μ§λ§μ νμ. μ΄μ°¨νΌ 맨 λ§μ§λ§μ μ€νλ¨.
order by 쑰건μ μ€λ³΅ / group by 쑰건μ μ€λ³΅
π μ¬λ¬κ° μ°κ³ μΆμΌλ©΄ , μ΄μ©νλ©΄ λλ€.
select * from orders o
group by payment_method , course_id
order by course_id , payment_method desc
where 쑰건
π μνλ 쑰건μ ν΄λΉνλ λ°μ΄ν°λ§ κ°μ Έμ¬ μ μλ μμ£Ό λλν μΉκ΅¬.
select payment_method, count(*) from orders
where course_title = "μΉκ°λ° μ’
ν©λ°"
group by payment_method;
where (νλλͺ ) like '% gmail %'
select name, count(*) from users
where email like '%gmail.com'
group by name;
where (νλλͺ ) between 'μΈμ λΆν°' and 'μ΄κ±° μ κΉμ§'
π created_at λ μ§κ° 2020-08-01 λΆν° ~ 2020-10-10 μ κΉμ§ ν΄λΉνλ μλ£λ§ κ°μ Έμ λ¬λΌλ λ§μ΄λ€.
select * from orders o
where created_at between '2020-08-01' and '2020-10-10'
where 쑰건 or 쑰건
π λμ€ νλλΌλ 쑰건μ ν΄λΉνλ€λ©΄ 보μ¬λ¬λΌλ μλ―Έμ΄λ€.
select * from orders o
where (created_at between '2020-08-01' and '2020-10-10') or
(created_at between '2020-07-01' and '2020-07-15')
where νλ in (쑰건)
select * from users
where name in ('μ **', 'μ΄**')
π νλλΌλ 쑰건μ ν΄λΉνλ€λ©΄ 보μ¬λ¬λΌλ μλ―Έμ΄λ€.
π or μ κ°μ μν ν¨.
π κ΄νΈ μμ 쑰건λ€μ μ½€λ§ (,) λ‘ κ΅¬λΆν΄μ λ£μ΄μ€λ€.
π in μ κ΄νΈ μμ λ€λ₯Έ select λ¬Έμ λ£μ μ μλ€.
select * from users u
where u.user_id in (select o.user_id
from orders o
where o.payment_method = 'kakaopay');
where 쑰건μ μ€λ³΅
π μ¬λ¬κ° μ°κ³ μΆμΌλ©΄ and μ΄μ©νλ©΄ λλ€.
select payment_method, count(*) from orders
where course_title = "μ±κ°λ° μ’
ν©λ°"
and email like '%naver.com'
group by payment_method
alias κΈ°λ₯
as λ³μΉμ§μ΄μ£ΌμΈμ
π sqlμ μΏΌλ¦¬λ¬Έμ΄ λ³΅μ‘ν΄ μ‘μλ ν·κ°λ¦¬μ§ μλλ‘ alias λ₯Ό ν΅ν΄ μ΄λ¦ μ§μ΄λ κΈ°λ₯.
π ν μ΄λΈ λͺ , νλλͺ λͺ¨λ λΆμΌ μ μλ€.
select * from orders as o
where o.course_title = "μ±κ°λ° μ’
ν©λ°";
select name, count(*) as freq from users
group by name