C.W.K.
Stream
Lesson 13 of 16 · published

GROUP BY 와 aggregate 함수

~14 min · queries, aggregation

Level 0스키마 새싹
0 XP0/86 lessons0/10 achievements
0/120 XP to next level120 XP to go0% complete

행을 summary 로 collapse

GROUP BY 가 steamroller — 행을 그룹으로 collapse, 각 그룹에 aggregate (COUNT, SUM, AVG, MIN, MAX) 실행. 개별 행 정체성 잃음; summary 얻음.

엄격한 룰

SELECT 의 모든 컬럼이 GROUP BY 에 있거나 또는 aggregate 안에 있어야. PostgreSQL 이 엄격히 강제 — MySQL 과 다르게, 거긴 random 값 조용히 고름 (그리고 틀림). 엄격함이 feature; 결과의 각 행이 실제로 뭐 의미하는지 생각하게 강제.

시간 버킷팅 위한 DATE_TRUNC

시계열 집계엔 DATE_TRUNC('day', timestamp_col) 가 각 timestamp 를 그 날 시작으로 truncate (또는 week/month/hour/minute). truncated 값으로 group by → 깨끗한 버킷.

Code

Whole-table summary·sql
SELECT COUNT(*)         AS total_orders,
       SUM(total)       AS revenue,
       AVG(total)       AS avg_order,
       MIN(total)       AS smallest,
       MAX(total)       AS largest,
       COUNT(DISTINCT customer_id) AS unique_customers
FROM   orders;
그룹당 GROUP BY·sql
SELECT u.name,
       COUNT(o.id)         AS order_count,
       SUM(o.total)        AS total_spent,
       ROUND(AVG(o.total), 2) AS avg_order
FROM   users u
JOIN   orders o ON o.user_id = u.id
GROUP  BY u.name
ORDER  BY total_spent DESC;
DATE_TRUNC 로 시간 버킷팅·sql
SELECT DATE_TRUNC('month', placed_at) AS month,
       COUNT(*)                       AS orders,
       SUM(total)                     AS revenue
FROM   orders
GROUP  BY DATE_TRUNC('month', placed_at)
ORDER  BY month;

-- 트래픽 분석 위한 시간대별
SELECT EXTRACT(HOUR FROM placed_at) AS hour_of_day,
       COUNT(*) AS orders
FROM   orders
GROUP  BY 1
ORDER  BY 1;

External links

Exercise

'월별 활성 유저' 쿼리 만들기: 지난 1년 월별 distinct 유저 카운트. 확장: self-join 또는 window function 으로 전월 카운트 옆에 (lesson 15 미리보기).

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.