杨大伟在路上

大数据第46天—Mysql练习题12道之一--杨大伟

我们有如下的用户访问数据

 

userId

visitDate

visitCount

u01

2017/1/21

5

u02

2017/1/23

6

u03

2017/1/22

8

u04

2017/1/20

3

u01

2017/1/23

6

u01

2017/2/21

8

U02

2017/1/23

6

U01

2017/2/22

4

要求使用SQL统计出每个用户的累积访问次数,如下表所示:

 

用户id

月份

小计

累积

u01

2017-01

11

11

u01

2017-02

12

23

u02

2017-01

12

12

u03

2017-01

8

8

u04

2017-01

3

3

 

 

 1 --建表
 2 drop table if exists test_one;
 3 create table test_one(
 4     userId bigint comment '用户id',
 5     visitDate bigint comment '访问日期',
 6     visitCount bigint comment '访问次数'
 7 ) comment '第一题';
 8 row format delimited fields terminated by '\t';
 9 
10 --插入数据
11 insert into table test_one values('u01','2017/1/21',5);
12 insert into table test_one values('u02','2017/1/23',6);
13 insert into table test_one values('u03','2017/1/22',8);
14 insert into table test_one values('u04','2017/1/20',3);
15 insert into table test_one values('u01','2017/1/23',6);
16 insert into table test_one values('u01','2017/2/21',8);
17 insert into table test_one values('u02','2017/1/23',6);
18 insert into table test_one values('u01','2017/2/22',4);
 1 --查询
 2 select
 3     userId `用户id`,
 4     visitDate `月份`,
 5     sum_mn `小计`,
 6     sum(sum_mn) over(partition by userId rows between UNBOUNDED PRECEDING and current row) `累计` 
 7 from
 8 (
 9     select
10         t1.userId,
11         t1.visitDate,
12         sum(t1.visitCount) sum_mn
13     from
14     (
15         select 
16             userId,
17             --date_format(to_date(from_unixtime(UNIX_TIMESTAMP(visitDate,'yyyy/MM/dd'))),'yyyy-MM') visitDate,
18             date_format(regexp_replace(visitdate,"/","-"),'yyyy-MM') visitDate,
19             visitCount
20         from test_one
21     ) t1
22     group by userId,visitDate
23 ) t2;

 

posted on 2020-08-25 20:54  浪子逆行  阅读(163)  评论(0编辑  收藏  举报

导航