테이블의 레코드를 그룹핑하여 그룹별로 다양한 정보를 계산
먼저 그룹핑을 할 필드를 결정 (하나 이상의 필드)
→ GROUP BY로 지정 (필드 이름을 사용하거나 필드 일련번호를 사용)
다음 그룹별로 계산할 내용을 결정
→ 여기서 AGGREGATE함수 사용(COUNT, SUM, AVG, MIN, LISTAGG, ...)
→ 보통 필드 이름을 지정하는 것이 일반적(alias)
SELECT
LEFT(ts,7) AS mon,
COUNT(1) AS session_count
FROM raw_data.session_timestamp
GROUP BY 1 -- GROUP BY mon, GROUP BY LEFT(ts,7)
ORDER BY 1;
SELECT
channel,
COUNT(1) AS session_count,
COUNT(DISTINCT userId) AS user_count
FROM raw_data.user_session_channel
GROUP BY 1 -- GROUP BY channel
ORDER BY 2 DESC; -- ORDER BY session_count DESC
SELECT
userId,
COUNT(1) AS count
FROM raw_data.user_session_channel
GROUP BY 1 -- GROUP BY userId
ORDER BY 2 DESC -- ORDER BY count DESC
LIMIT 1;
SELECT
TO_CHAR(A.ts, 7) AS month -- TO_CHAR(A.ts, 'YYYY-MM')
COUNT(DISTINCT B.userId) AS mau
FROM raw_data.sessin_timestamp A
JOIN raw_data.user_session_channel B ON A.sessionid = B.sessionid
GROUP BY 1
ORDER BY 1 DESC;
SELECT
TO_CHAR(A.ts, 'YYYY-MM') AS month,
channel,
COUNT(DISTINCT B.userId) AS mau
FROM raw_data.session_timestamp A
JOIN raw_data.user_session_channel B ON A.sessionId = B.sessionId
GROUP BY 1,2
ORDER BY 1 DESC, 2;
SELECT를 가지고 테이블 생성
CREATE TEBLE adhoc.table_name AS
SELECT B.*, A.ts
FROM raw_data.session_timestamp A
JOIN raw_data.user_session_channel B
ON A.sessionId = B.sessionId;
SELECT
TO_CHAR(ts, 'YYYY_MM') AS month,
COUNT(DISTINCT userId) AS mau
FROM adhoc.table_name
GROUP BY 1
ORDER BY 1 DESC;
중복된 레코드들 체크하기
다음 두 개의 카운트를 비교
SELECT COUNT(1)
FROM adhoc.table_name;
SELECT COUNT(1)
FROM (
SELECT DISTINCT userId, sessionId, ts, channel
FROM adhoc.table_name
);
CTE를 사용해서 중복 제거 후 카운트 해보기
With ds AS(
SELECT DISTINCT userId, sessionId, ts, channel
FROM adhoc.table_name
)
SELECT COUNT(1)
FROM ds;
최근 데이터의 존재 여부 체크하기
SELECT MIN(ts), MAX(ts)
FROM adhoc.table_name;
SELECT sessionId, COUNT(1)
FROM adhoc.table_name
GROUP BY 1
ORDER BY 2 DESC
LIMIT 1;
SELECT
COUNT(CASE WHEN sessionId is NULL THEN 1 END) sessionId_null_count,
COUNT(CASE WHEN userId is NULL THEN 1 END) userId_null_count,
COUNT(CASE WHEN ts is NULL THEN 1 END) ts_null_count,
COUNT(CASE WHEN channel is NULL THEN 1 END) channel_null_count, FROM adhoc.table_name;