SQL
SQL - Join & Group by
남생이a
2024. 3. 20. 18:04
1. 고객명 Antonio Moreno이 1997년에 주문한 주문 상품정보를 고객 주소, 주문 아이디, 주문일자, 배송일자, 배송 주소 및 주문 상품아이디, 주문 상품명, 주문 상품별 금액, 주문 상품이 속한 카테고리명, supplier명을 구할 것.
select a.contact_name, a.address, b.order_id, b.order_date, b.shipped_date, b.ship_address
, c.product_id, d.product_name, c.amount, e.category_name, f.contact_name as supplier_name
from nw.customers a
join nw.orders b on a.customer_id = b.customer_id
join nw.order_items c on b.order_id = c.order_id
join nw.products d on c.product_id = d.product_id
join nw.categories e on d.category_id = e.category_id
join nw.suppliers f on d.supplier_id = f.supplier_id
where a.contact_name = 'Antonio Moreno'
and b.order_date between to_date('19970101', 'yyyymmdd') and to_date('19971231', 'yyyymmdd')
2. 부서명 SALES와 RESEARCH 소속 직원별로 과거부터 현재까지 모든 급여를 취합한 평균 급여
with
temp_01 as
(
select a.dname, b.empno, b.ename, b.job, c.fromdate, c.todate, c.sal
from hr.dept a
join hr.emp b on a.deptno = b.deptno
join hr.emp_salary_hist c on b.empno = c.empno
where a.dname in('SALES', 'RESEARCH')
order by a.dname, b.empno, c.fromdate
)
select empno, max(ename) as ename, avg(sal) as avg_sal
from temp_01
group by empno;
3. deptno로 group by하고 job으로 pivoting
select sum(case when job = 'SALESMAN' then sal end) as sales_sum
, sum(case when job = 'MANAGER' then sal end) as manager_sum
, sum(case when job = 'ANALYST' then sal end) as analyst_sum
, sum(case when job = 'CLERK' then sal end) as clerk_sum
, sum(case when job = 'PRESIDENT' then sal end) as president_sum
from emp;
4. group by Pivoting시 조건에 따른 건수 계산 시 sum()을 이용
select deptno, count(*) as cnt
, sum(case when job = 'SALESMAN' then 1 else 0 end) as sales_cnt
, sum(case when job = 'MANAGER' then 1 else 0 end) as manager_cnt
, sum(case when job = 'ANALYST' then 1 else 0 end) as analyst_cnt
, sum(case when job = 'CLERK' then 1 else 0 end) as clerk_cnt
, sum(case when job = 'PRESIDENT' then 1 else 0 end) as president_cnt
from emp
group by deptno;
5. Group by rollup : deptno + job레벨 외에 dept내의 전체 job 레벨(결국 dept레벨), 전체 Aggregation 수행.
select deptno, job, sum(sal)
from hr.emp
group by rollup(deptno, job)
order by 1, 2
6. 상품 카테고리 + 상품별 매출합 구하되, 상품 카테고리 별 소계 매출합 및 전체 상품의 매출합을 함께 구하기
select c.category_name, b.product_name, sum(amount)
from nw.order_items a
join nw.products b on a.product_id = b.product_id
join nw.categories c on b.category_id = c.category_id
group by rollup(c.category_name, b.product_name)
order by 1, 2
7. Group by cube : 상품 카테고리, 상품별, 주문처리직원별 가능한 결합으로 Group by 수행
select c.category_name, b.product_name, e.last_name||e.first_name as emp_name, sum(amount)
from nw.order_items a
join nw.products b on a.product_id = b.product_id
join nw.categories c on b.category_id = c.category_id
join nw.orders d on a.order_id = d.order_id
join nw.employees e on d.employee_id = e.employee_id
group by cube(c.category_name, b.product_name, e.last_name||e.first_name)
order by 1, 2, 3