sql实战记录
- 给一个表ord,包括user_id(用户id),goods_id(商品id),goods_num(购买商品数),ord_amt(购买金额),creat_time(购买时间)
求最近30天商品的平均价格
select goods_id as '商品id',sum(ord_amt)/sum(goods_num) as '近30天平均价格' from (select goods_id,sum(ord_amt),sum(goods_num) from ord) where datediff(curdate(),convert(creat_time,date))<=30 group by goods_id核心的部分是最近30天的处理代码,关于返回当前日期mysql中有如下三种写法:
SELECT NOW(),CURDATE(),CURTIME()结果:
NOW() | CURDATE() | CURTIME() |
---|---|---|
2008-12-29 16:25:46 | 2008-12-29 | 16:25:46 |
2. 两个表:
pv_log(用户浏览记录表):pv_id(页面id),user_id(用户id),creat_time(访问时间)
dimuser(用户注册记录表):user_id(用户id),age(年龄),creat_time(注册时间)
统计浏览不同页面数的用户对应的平均年龄
--考虑了访问时间和注册时间的年龄间隔 select a.pv_id,AVG(a.newyear-b.birthyear) from (select pv_id,user_id,year(creat_time) as newyear from pv_log group by pv_id,user_id,year(creat_time)) a left join (select user_id,(year(creat_time)-age) as birthyear from dim_user group by user_id) b on a.user_id = b.user_id
3.两张表
tbl_ordr(用户订单表):user_id(用户id), ordr_id(订单号), ordr_goods(订单商品id), ordr_time(预定时间)
tblclk(用户商品点击明细表):clk_id(点击id), user_id, clk_time(点击时间), clk_goods(点击的商品id,和ordr_goods对应)
用户点击商品之后的订单算是这次点击产生的订单;多次点击后产生的订单,算订单创建前最后一次点击产生的订单,求有订单商品的点击及订单号
--将订单表和点击商品明细表关联,找出下单商品所有的记录 with base0 as ( select a.usr_id,a.ordr_id,a.ord_goods,b.clk_id,max(b.clk_time) over(partition by clk_goods) from tbl_order a left join tbl_clk b on a.usr_id = b.usr_id and a.ord_goods = b.clk_goods where b.clk_time < a.ordr_time ) select clk_id,order_id from base0