1.数据分析之 mysql:mysql基础习题

一、介绍

 这是关于mysql比较经典的练习题,在我们学习完mysql数据库以后,可以通过练习得到巩固

二、案例介绍

orderinfo  订单详情表( orderid  订单id;userid    用户id; isPaid    是否支付;price    付款价格; paidTime  付款时间)

userinfo  用户信息表(userid   用户id; sex   用户性别; birth  用户出生日期)

三、题目要求及答案

1、统计不同月份的下单人数

 # 首先明确一点,下单人数应该是已经支付的人数,并且用户可能不止一次下单,就需要去重,不同月份意味着分组

 # 代码

 """

 select  year(paidTime),  month(paidTime),  count(distinct userid) as cons

from   orderinfo

where   isPaid="已支付"  and   paidTime<>'0000-00-00 00:00:00'

group by year(paidTime),month(paidTime);

 """

2、统计用户三月份的回购率和复购率

知识点: 复购率:当月购买了多次的用户占占当月用户的比例

            回购率:上月购买的用户中有多少用户本月又再次购买

# 思路:三月份的复购率,也就是先统计出总用户人数,后面统计购买多次的人数,相比较就可以了

select count(ct),sum(if(ct>1,1,0) 

(select userid,count(*) as ct

from orderinfo

where isPaid="已支付"  and   month(paidTime) = 3;

group by userid) a;

# 回购率(第一种解读:直接使用月份,month=3和4,分别算出数量,在join拿到数据,不做过多解读)

第二种解答:标准模板

select t1.dt, count(t1.userid),count(t2.userid),count(t2.userid)/count(t1.userid) as "回购率"

(select userid,date_format(paidtime,"%Y-%m-01") as dt

from orderinfo

where ispaid = "已支付" 

group by userid,date_format(paidtime,"%Y-%m-01")) t1

left join

(select userid,date_format(paidtime,"%Y-%m-01") as dt

from orderinfo

where ispaid = "已支付" 

group by userid,date_format(paidtime,"%Y-%m-01")) t2

on t1.userid = t2.userid 

and t1.dt = date_sub(t2.dt,interval 1 month)

group by t1.dt

3、统计男女用户消费频次是否有差异

select

  sex,

  avg(cons) as avg_cons

from (select

  a.userid,

  sex,

  count(1) as cons

from orderinfo a

inner join (select * from userinfo where sex<>'') b

on a.userid=b.userid

group by a.userid,sex) a

group by sex;

4、统计多次消费的用户,第一次和最后一次消费间隔是多少天

1.统计多次消费的用户,取时间(分组后取时间)

select userid,min(paidtime),max(paidmax),datediff(max(paidmax),min(paidtime)) as "时间间隔"

 from userinfo

where ispaid = "已支付"

group by userid

having count(1) >1;

5、统计不同年龄段,用户的消费金额是否有差异

select

  age,

  avg(cons),

  avg(prices)

from (select

  a.userid,

  age,

  count(1) as cons,

  sum(price) as prices

from orderinfo a

inner join (select

  userid,

  birth,

  now(),

  ceil(timestampdiff(year,birth,now())/10) as age

from userinfo

where birth>'1901-00-00') b

on a.userid=b.userid

group by a.userid,age) a

group by age;

 6、统计消费的二八法则,消费的top20%用户,贡献了多少消费额

select

  count(1) as cons,

  sum(total_price) as all_price

from (

select

  userid,

  sum(price) as total_price

from orderinfo a

where isPaid="已支付"

group by userid

order by total_price desc

limit 17000) b ;

你可能感兴趣的:(1.数据分析之 mysql:mysql基础习题)