面试遇到的订单表sql的解决方案

 

对于以下需求:用户表:users (user_id  int)
订单表:order_tb(user_id int, or_time  date, or_money double)
求以下用户:
一月下过单,二月份没有下过单的三月份下单用户
的如下指标:
三月份订单金额大于100的订单数,三月份第一笔订单和最后一笔订单的订单金额。(每个用户的哦)

 

网上求得如下解答,比自己之前写的几百行好多了。不知道有没有其它解决方案

with us1 as  (select user_id,or_time,or_money,
                    sum(nvl(case when  to_char(or_time,'MM') = '01' then 1 end,0)) over (partition by user_id) m1,
                    sum(nvl(case when  to_char(or_time,'MM') = '02' then 1 end,0)) over (partition by user_id) m2,
                    sum(nvl(case when  to_char(or_time,'MM') = '03' then 1 end,0)) over (partition by user_id) m3,
                    sum(case when  to_char(or_time,'MM') = 03 and or_money > 100 then 1 end) over (partition by user_id) cnt
                    from order_tb
                    where or_time between to_date('20170101','YYYYMMDD') and to_date('20170331','YYYYMMDD')),
mo1 as (select distinct user_id,
            case when  to_char(or_time,'MM') = 03 then first_value(or_money) over (partition by user_id order by or_time) end f1v,
            case when  to_char(or_time,'MM') = 03 then last_value(or_money) over (partition by user_id order by or_time range between unbounded preceding and unbounded following) end f3l,
            cnt from (select * from us1 where m2=0 and m1 >0 and m3 >0 and or_time between to_date('20170301','YYYYMMDD') and to_date('20170331','YYYYMMDD')))

转载于:https://www.cnblogs.com/qiuhong10/p/7678046.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值