[Database] cube, with

cube


cube는 중간 합계를 낼 때 사용된다. 다음 sql문을 실행해보자

select item_cd, unit, sum(qty)
from procure_procure_request
where (procure_request_date = '20170103' or procure_request_date = '20170104')
group by cube(item_cd, unit)
order by unit;

실행하면 item_cd 별로 해당되는 procure_request_date의 qty 합계를 내는 것을 확인할 수 있다.

with


어떤 특정한 데이터들을 뭉치로 묶고 그 중에 뽑아서 쓸 때 with를 쓴다.

with get_some(procure_request_no, item_cd, qty)
as
(select procure_request_no, item_cd, qty
from procure_procure_request
where procure_request_date = '20170103'
or procure_request_date = '20170104'
or procure_request_date = '20170105')
select * from get_some order by qty asc;

with 옆에 가상 테이블을 쓰고 () 안에 특정 데이터를 뽑을 select 문을 쓴다. 그런다음 괄호를 닫고 뽑아서 쓸 데이터를 가져올 select 문을 쓴다. 이 with 문을 아래와 같이 sum()로 응용할 수 있다.

with get_some(procure_request_no, item_cd, qty)
as
(select procure_request_no, item_cd, qty
from procure_procure_request
where procure_request_date = '20170103'
or procure_request_date = '20170104'
or procure_request_date = '20170105')
select sum(qty) from get_some order by qty asc;

계층형 with


위의 with를 계층형으로 만들어 쓸 수 있다. with는 데이터를 한 덩어리로 만들 것을 이용해 각 덩어리를 계층으로 매겨서 만는 방법이다. 계층을 잘 보여주는 데이터가 군데이므로 임시적으로 컬럼 iid, name, master, position 이 있는 테이블 infinty를 만들었다. 그리고 master가 직속 상사이므로 master가 ‘없음’으로 시작하여 master와 name이 같은 경우 계층을 1씩 증가하여 만드는 sql문이 아래의 sql문이다.

WITH ifout(iid, name, master, position, ilevel)
as
(
   ( select ifl.iid
           , ifl.name
           , ifl.master
           , ifl.position
           , 0
    from infinty    ifl
    where ifl.master = '없음')
    union all
  (  select if2.iid
           , if2.name
           , if2.master
           , if2.position
           , ifout.ilevel + 1
    from infinty    if2
    inner join ifout
    on if2.master = ifout.name )
    )
    select * from ifout order by ifout.iid;

이런 계층형 with 문은 매우 어려우므로 이해가 안된다고 좌절하지 말자






© 2021.11. by 21thkafka

Powered by 21thkafka