각 고객별로 주문 금액 최대값이 600달러 이상인 데이터만 가져와서 내림차순으로 정렬하려고 한다.
이때 group by 뒤에는 where이 아니라 having을 써준다.
select c.first_name, c.last_name, max(o.amount) as MAX
from customers c
join orders o
on c.id = o.customer_id
group by c.id having max(o.amount) >= 600
order by MAX desc;
case로 시작 end로 끝나며 when을 통해 조건문과 then을 통해 원하는 값을 넣어준다.
-- stock_quantity 가 0 ~ 50 사이면, * (별표한개)
-- stock_quantity 가 51 ~ 100 사이면, ** (별표두개)
-- stock_quantity 그 외에는 *** (별표3개)
select *,
case
when stock_quantity between 0 and 50 then '*'
when stock_quantity between 51 and 100 then '**'
else '***'
end as stars
from books;
select name, year(birthdate)
from people2;
select name, month(birthdate)
from people2;
select name, day(birthdate)
from people2;
select name, dayofweek(birthdate)
from people2;
select name, dayname(birthdate)
from people2;
select name, hour(birthtime)
from people2;
select name, minute(birthtime)
from people2;
select name, second(birthtime)
from people2;
아래는 날짜 포맷과 시간 계산방법이다.
-- 2000-11-11 03:50 에 태어났습니다.
select date_format(birthdt, '%Y-%m-%d %H:%i 에 태어났습니다.')
from people2;
-- birthdate 컬럼과 현재시간의 차이를 가져오세요
select datediff(now(), birthdate)
from people2;
-- birthdate에 36일 후는??
select date_add(birthdate, interval 36 day);
아래처럼 데이터를 insert하면 created_at에 timestmap로 현재시간이 저장된다.
timestamp는 1970년 1월 1일 자정을 0으로 시작해서(정확하게 표현하면 00:00:00 UTC on January 1, 1970)~
특정 시점까지 얼마나 많은 초(second) 단위의 시간이 지났는지를 통해 특정 시점을 표기하는 방식이다.
create table comments (
id int unsigned not null auto_increment primary key,
content varchar(100),
created_at timestamp default now()
);
insert into comments
(content)
values
('사과 진짜 맛있나요??????????');