mysql에서 월별 가입자 누적 갯수를 추출하고 싶습니다.
member 테이블은 아래와 같습니다.
Table : member
ID | CRT_DT (가입일) |
account1 | 2019-10-11 14:15:40 |
account2 | 2019-11-01 14:24:55 |
account3 | 2019-11-01 14:58:51 |
account4 | 2019-12-24 17:21:54 |
account5 | 2020-01-03 11:36:43 |
account6 | 2020-02-03 11:58:27 |
집계 결과
MONHT | COUNT |
2019-10 | 1 |
2019-11 | 3 |
2019-12 | 4 |
2020-01 | 5 |
2020-02 | 6 |
오라클, mssql에서 사용하는 sum() over() 함수는 mysql에서 사용할 수 없는것 같더라구요.
해결방법을 알려주시거나 힌트를 주셔도 감사 하겠습니다.
도움 부탁드립니다.
아.... sum() over() 사용 못한다는걸 못봤었네요~ with t as (select 'acnt1' id, '2019-10-11 14:15:40' crt_dt union all select 'acnt2' id, '2019-11-01 14:24:55' crt_dt union all select 'acnt3' id, '2019-11-01 14:58:51' crt_dt union all select 'acnt4' id, '2019-12-24 17:21:54' crt_dt union all select 'acnt5' id, '2020-01-03 11:36:43' crt_dt union all select 'acnt6' id, '2020-02-03 11:58:27' crt_dt ) select date_format(crt_dt, '%Y-%m') as months , sum(count(*)) over(order by months) from t group by date_format(crt_dt, '%Y-%M') order by months ;
WITH t AS ( SELECT 'account1' id, '2019-10-11 14:15:40' crt_dt UNION ALL SELECT 'account2', '2019-11-01 14:24:55' UNION ALL SELECT 'account3', '2019-11-01 14:58:51' UNION ALL SELECT 'account4', '2019-12-24 17:21:54' UNION ALL SELECT 'account5', '2020-01-03 11:36:43' UNION ALL SELECT 'account6', '2020-02-03 11:58:27' ) -- 1. @변수 사용 SELECT ym , cnt , @cnt := @cnt + cnt tot FROM (SELECT DATE_FORMAT(crt_dt, '%Y-%m') ym , COUNT(*) cnt FROM t GROUP BY DATE_FORMAT(crt_dt, '%Y-%m') ) a , (SELECT @cnt := 0) b ; -- 2. Self Join SELECT a.ym , a.cnt , SUM(b.cnt) tot FROM (SELECT DATE_FORMAT(crt_dt, '%Y-%m') ym , COUNT(*) cnt FROM t GROUP BY DATE_FORMAT(crt_dt, '%Y-%m') ) a INNER JOIN (SELECT DATE_FORMAT(crt_dt, '%Y-%m') ym , COUNT(*) cnt FROM t GROUP BY DATE_FORMAT(crt_dt, '%Y-%m') ) b ON a.ym >= b.ym GROUP BY a.ym, a.cnt ;