당니이
다은이의 컴퓨터 공부
당니이
전체 방문자
오늘
어제
  • 분류 전체보기 (140)
    • Achieved 👩🏻 (14)
      • 생각들 (2)
      • TIL (6)
      • Trial and Error (1)
      • Inspiration ✨ (0)
      • 미국 박사 준비 🎓 (1)
    • Computer Vision💖 (39)
      • Basic (9)
      • Video (5)
      • Continual Learning (7)
      • Generative model (2)
      • Domain (DA & DG) (5)
      • Multimodal (8)
      • Multitask Learning (1)
      • Segmentation (1)
      • Colorization (1)
    • RL 🤖 (4)
    • Autonomous Driving 🚙 (11)
      • Geometry (4)
      • LiDAR 3D Detection (1)
      • Trajectory prediction (2)
      • Lane Detection (1)
      • HDmap (3)
    • Linux (15)
    • PyTorch👩🏻‍💻 (10)
    • Linear Algebra (2)
    • Python (5)
    • NLP (11)
      • Article 📑 (1)
    • Algorithms 💻 (22)
      • Basic (8)
      • BAEKJOON (8)
      • Programmers (2)
    • ML (1)
      • 통계적 머신러닝(20-2) (1)
    • SQL (3)
    • 기초금융 💵 (1)

블로그 메뉴

  • 홈
  • About me

공지사항

인기 글

태그

  • LLM
  • 리눅스
  • continual learning
  • 백트래킹
  • 자료구조
  • CV
  • 알고리즘
  • 코딩테스트
  • til
  • NLP
  • pytorch
  • Python
  • domain generalization
  • CL
  • domain adaptation
  • Linux
  • dfs
  • 백준
  • Incremental Learning
  • conda

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
당니이

다은이의 컴퓨터 공부

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의 특성 때문이다)

 

반응형
저작자표시 (새창열림)

'SQL' 카테고리의 다른 글

[SQL] 데이터 조인(Inner, Outer, Full outer, Cross join)  (0) 2021.02.12
[SQL] 데이터 조회와 필터링 (select, order, where, limit, in , between)  (0) 2021.02.05
    'SQL' 카테고리의 다른 글
    • [SQL] 데이터 조인(Inner, Outer, Full outer, Cross join)
    • [SQL] 데이터 조회와 필터링 (select, order, where, limit, in , between)
    당니이
    당니이
    씩씩하게 공부하기 📚💻

    티스토리툴바