name date pv A 2015-01 5 A 2015-01 15 B 2015-01 5 A 2015-01 8 B 2015-01 25 A 2015-01 5 A 2015-02 4 A 2015-02 6 A 2015-02 4 B 2015-02 10 B 2015-02 5 A 2015-03 16 A 2015-03 22 B 2015-03 23 B 2015-03 10 B 2015-03 11
需求: 求每个用户截止每月为止的最大单月访问次数和累计到该月的总访问次数
实现
自连接方式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
select a.name,a.date,a.pv,max(b.pv),sum(b.pv) from ( selectname,date,sum(pv) pv from demo groupbyname,date ) a join ( selectname,date,sum(pv) pv from demo groupbyname,date ) b on a.name=b.name where a.date >= b.date groupby a.name,a.date,a.pv;
窗口函数方式
1 2 3 4 5 6 7 8 9
select a.name,a.date,a.pv, sum(a.pv) over (partitionby a.name orderby a.date) sumpv, max(a.pv) over (partitionby a.name orderby a.date) maxpv from ( selectname,date,sum(pv) pv from demo groupbyname,date ) a;