SQL

[SQL] 데이터 집계(Group by, Having, Grouping set, Roll up, Cube)

당니이 2021. 2. 13. 23:55
반응형

데이터 집계는 조인 다음으로 정말 중요하다! 오늘은 집계 함수에 대해 포스팅해보고자 한다~_~

1. Group by

각 그룹에 대한 합계, 평균, 카운트 등을 계산

select segment, count(quantity) from sales
group by segment;

특이한 점은 select 다음의 count로 groupby aggregation 을 지정한다는 점! 
그래서 이 부분을 마지막에 코딩하는 것도 방법인 것 같다

+) Group by로 unique한 값만 출력할 수도 있다

--1. groupby 이용
select customer_id from payment 
group by customer_id;

--2. select distinct 이용
select distinct customer_id from payment;  -

 


2. Having 

Group by 결과를 특정 조건으로 필터링하는 기능! Group by 바로 뒤에 위치한다

cf) Where 절은 Groupby 적용 전 개별 조건을 설정하고, Having은 Group by 절 뒤에서 조건을 설정한다
select customer_id, sum(amount) as amount_sum, count(amount) as amount_count from payment 
group by customer_id --고객 id로 groupby
having sum(amount) > 200 --groupby 결과 중 특정 조건의 열만 출력 
order by sum(amount) desc
;

 


다음은 Group by 다음에 쓰는 고급 집계 함수들이다!

3. Grouping Set 

여러 경우의 Group by set을 자동으로 출력해줌. 
Group by를 여러번 하지 않아도 자동으로 full outer join 처럼 출력해준다
단, 꼭 Group by 다음에 써줘야 한다 !

-- grouping sets
select brand, segment, sum(quantity) from sales 
group by grouping sets(
(brand, segment), (brand), (segment), ()
);

→ brand & segment별, brand별, segment별, 전체 합계 차례로 출력


4. Roll up

grouping 칼럼의 소계를 생성하는데 사용

select
	brand,
	segment,
	sum(quantity)
from sales
group by
	rollup(brand,segment)
order by brand,segment;

Roll up 뒤에 ( brand, segment ) 일 때, 
1) Brand & Segment 별 합계
2) Roll up 절에 맨 앞에 쓴 칼럼별 합계
3) 전체 합계 

를 출력한다!


 

5. Cube

다차원 소계를 생성하는데 사용됨! 여러가지 조합을 고려해 group by를 하는 느낌이다. 

출처 : 패스트캠퍼스

select
	brand,segment,sum(quantity)
from
	sales
group by
	cube (brand,segment)
order by
	brand,segment;

cube (brand, segment) 이면 총 4개의 조합을 고려하게 된다

cf) Roll up과 비교하면, 만약 roll up(brand, segment)일 때는 brand별 합계만 나오고 segment별 합계는 나오지 않는다. (맨 앞의 칼럼만 고려해 연산하는 roll up의 특성 때문이다)

 

반응형