面试查漏补缺

sql

问题1:
有两张表,table1描述用户最近30天内访问的天数,有3个字段:日期log_date,user_id,访问天数,table2描述每个用户的pv,有3个字段:日期,uid,pv
求3.14这天最近三十天内访问天数在1-10,10-20,20-30三个区间的用户的总pv和总uv(pv指这个用户的点击次数,可能每个用户有很多次,uv指每个人的访问次数,每个用户只能是0或者1)
总pv
Select
sum(case when 1=<table1.访问天数 and table1.访问天数<=10 then pv else 0 end) as sum1,
sum(case when 10<table1.访问天数 and table1.访问天数<=20 then pv else 0 end) as sum2,
sum(case when 20<table1.访问天数 and table1.访问天数<=30 then pv else 0 end) as sum3
From table1 (不要写from table1,table2 where table1. …= table2. …)
join table2
on log_date=’20220314’ and table_1.user_id= table_2.user_id
总uv:
Select
sum(case when 1=<table1.访问天数<=10 then 1 else 0) as sum1,
sum(case when 10< table1.访问天数<=20 then 1else 0) as sum2,
sum(case when 20< table1.访问天数<=30 then 1 else 0) as sum3
From table1,table2
Where log_date=’20220314’ and table_1.user_id= table_2.user_id
Group by uid
这样是不对的 groupby是分组,select后的内容相当于是对group by中每一组的内容进行操作,所以这里相当于对每个uid的内容求sum() 所以不对,应该写一个子查询A写查出每个用户的uv再sum(每个用户可能这天点了几十次所以pv是好几十但是他的uv)

正确写法:
with query1 as (
select user_id,count(*) as uv
from table2
where log_date=’20220314’
group by user_id
)

Select sum (case when 1=<table1.访问天数 and table1.访问天数<=10 then uv else 0) as sum_uv1,
sum(case when 10< table1.访问天数 and table1.访问天数<=20 then uv else 0) as sum_uv2,
sum(case when 20< table1.访问天数 and table1.访问天数<=30 then uv else 0) as sum_uv3
From query1 join table1
on query1.user_id=table1.user_id

在query1的子查询中group by user_id之后相当于对于每个user_id的这个组进行count计数,每个组只有一个user_id,所以也就是对于每个user_Id都只执行了一次count,也就是得到了每个user_Id和其uv是1的这样一个临时表,第一个子查询就得到每个用户的uv
然后再select从query1中对于符合条件的uv加和

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值