[Database] count 표준편차 분산, Roll up, grouping_id

count 표준편차 분산


count에 앞서 stddev와 variance라는 분산, 표준편차 내는 통계 함수가 있다. 쓰는 방법은 다음과 같은데 연구 개발쪽이나 심도 높은 경제학에서 수학을 필요할 때 제외하고는 쓸 일이 거의 없다고 한다.

select stddev(cost)
from procure_item
where (item_cd > '006' and item_cd < '0014');
select variance(cost)
from procure_item
where (item_cd > '006' and item_cd < '0014');

Roll up


Roll up은 총 합계를 낼 때 사용한다. 우선 group by로 sum 함수로 합계를 내는 sql문을 써보자

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

이러면 각 유닛마다 수량 합계가 sum함수로 나온다. 이 수량 합계의 총 합계를 내고 싶을 때 group by 옆에 roll up을 써준다.

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

그러면 각 유닛마다의 수량 합계와 null 값 옆에 총 합계가 찍히는 것을 볼 수 있다. 이런 기능이기 때문에 roll up은 합계를 낼 때 쓰인다.

grouping_id

grouping_id는 위 sql문처럼 합계나 최대값등 통계를 낼 때 각 아이디의 해당 값을 표시한다. 예를 들어 바로 위의 sql 문에 grouping_id를 추가하면 총 합계인 null 값 오른쪽에 1이 표시됨을 볼 수 있다.

select unit, sum(qty), grouping_id(unit)
from procure_procure_request
where (procure_request_date = '20170103' or procure_request_date = '20170104')
group by rollup(unit);

이를 실무에서 decode라는 함수를 이용하여 다음과 같은 sql문으로 응용할 수 있다.

select unit, sum(qty), grouping_id(unit),
    decode(grouping_id(unit), 0, '자료', '합계')
from procure_procure_request
where (procure_request_date = '20170103' or procure_request_date = '20170104')
group by rollup(unit);

참고로 decode 함수와 같은 기능이지만 decode에서 할 수 없는 like 기능을 쓸 수 있는 case when도 있다. case when으로 변경하면 다음과 같다.

select unit, sum(qty), grouping_id(unit),
       case grouping_id(unit)
       when 1
       then '합계'
       else '자료'
       end as groupingName
from procure_procure_request
where (procure_request_date = '20170103' or procure_request_date = '20170104')
group by rollup(unit);






© 2021.11. by 21thkafka

Powered by 21thkafka