select dept_name, avg_salary
from ( select dept_name, avg(salary) as avg_salary
from instructor
group by dept_name ) // group별 salary 평균이 있는 2개 column짜리 table을 만든다
where avg_salary > 42000;
select dept_name, avg(salary) as avg_salary
from instructor
group by dept_name
having avg(salary) > 42000
// 이게 가장 simple하다
select dept_name, avg_salary
from ( select dept_name, avg(salary)
from instructor
group by dept_name)
as dept_avg(dept_name, avg_salary) // table에 새로운 이름을 준다
where avg_salary > 42000;
실제 저장하는 애들은 : CREATE로 만든거
with max_budget(value) as // 새로운 table column 하나. tuple도 하나이다.
(select max(budget)
from department)
select department.name
from department, max_budget
where deaprtment.budget = max_budget.value
// 이게 종료되면 max_budget은 없어진다.
with dept_total(dept_name, value) as // 학과별 salary 총합을 나타내는 table
(select dept_name, sum(salary)
from instructor
group by dept_name),
dept_total_avg(value) as // 하나의 column, 하나의 tuple
(select avg(value)
from dept_total)
select dept_name
from dept_total, dept_total_avg
where dept_total.value > dept_total_avg.value
// 이게 끝나면 두 개의 temporary table은 끝.
select dept_name,
(select count(*)
from instructor
where department.dept_name = instructor.dept_name)
as num_instructor
from department
delete from instructor
delete from instructor
where dept_name = 'Finance'
delete from instructor
where dept_name in ( select dept_name
from department
where building = 'Watson');
delete from instructor
where salary < (select avg(salary)
from instructor);
insert into course
values('CS-437', 'Database Systems', 'Comp.Sci.', 4);
// 순서가 바뀌지 않도록 주의하자
equivalently,
insert into course(course_id, title, dept_name, credits)
values('CS-437', 'Database Systems', 'Comp.Sci.', 4);
insert into student
values('3003', 'Green', 'Finance', null);
insert into instructor
select ID, name, dept_name, 18000
from student
where dept_name = 'Music' and total_cred > 144;
update instructor
set salary = salary * 1.05
update instructor
set salary = salary * 1.05
where salary < 70000;
update instructor
set salary = salary * 1.05
where salary < (select avg(salary)
from instructor);
update instructor
set salary = salary * 1.03
where salary > 100000;
update instructor
set salary = salary * 1.05
where salary <= 100000;
update instructor
set salary = case
when salary <= 100000 then salary * 1.05
else salary * 1.03
end
case
when pred1 then result1
when pred2 then result2
...
when predn then resultn
else result0
end
update student
set tot_cred = (select sum(credits) // tot_cred을 새로 계산한다.
from takes, course
where takes.course_id = course.course_id and
student.ID = takes.ID and
takes.grade <> 'F' and
takes.grade is not null); // grade가 null인건 지금 수강중인 걸 의미한다.
update student
set tot_cred = (select case
when sum(credits) is not null then sum(credits)
else 0
end
from takes, course
where takes.course_id = course.course_id and
student.ID = takes.ID and
takes.grade <> 'F' and
takes.grade is not null);