问题

在Hive或者ODPS中,怎么用sql实现分钟级的趋势图?比如从交易表中,如何统计0点到每分钟的交易趋势图?

原表:trade_A(trade_id,pay_time(格式是2020-08-05 10:30:28),pay_gmv)。希望用sql实现分钟级的0点到当前分钟的GMV。
结果表:result_A(minute_rn(分钟顺序),pay_gmv_td(每分钟的交易额,都是0点到当前分钟的累加值))。
以下是示例数据:


with tmp as (
    select 101 as trade_id,'2020-08-05 00:30:28' as pay_time,100 as pay_gmv
    union all
    select 102 as trade_id,'2020-08-05 00:30:58' as pay_time,200 as pay_gmv
    union all
    select 103 as trade_id,'2020-08-05 00:35:28' as pay_time,300 as pay_gmv
    union all
    select 104 as trade_id,'2020-08-05 01:36:28' as pay_time,400 as pay_gmv
    union all
    select 105 as trade_id,'2020-08-06 00:20:28' as pay_time,500 as pay_gmv
    union all
    select 106 as trade_id,'2020-08-06 00:21:28' as pay_time,600 as pay_gmv
)

sql解答

其实这个题的核心就是使用sql生成分钟级的序列,与之前SQL面试题挑战08:补全缺失日的月销售累计的场景类似。然后关联原表,做开窗累加即可。而且生成分钟级的这段代码是可以收藏以后作为工具代码使用的。

select
minute_rn
-- 开窗累加即可
,sum(pay_gmv) over(partition by date_format(minute_rn,'yyyy-MM-dd') order by minute_rn) as pay_gmv_td -- 按当前时间按天开窗累加,得到每分钟的累计销售额
from
(
    -- 根据数据中的日期生成连续的分钟序列。从最小日期的0点到最大日期的23:59分
    select
    t1.minute_rn
    ,nvl(t2.pay_gmv,0) as pay_gmv
    from
    (
        select
        from_unixtime(unix_timestamp(t1.min_pay_time)+tab.pos*60,'yyyy-MM-dd HH:mm') as minute_rn
        from
        (
            select
            min(date_format(pay_time,'yyyy-MM-dd 00:00:00')) as min_pay_time --取最小日期
            ,max(date_format(pay_time,'yyyy-MM-dd 23:59:59')) as max_pay_time --取最大日期
            from tmp
        )t1
        lateral view posexplode(split(repeat(',',(unix_timestamp(max_pay_time)-unix_timestamp(min_pay_time))/60),',')) tab as pos,val
    )t1
    left join
    (   
        -- 先按同分钟的数据进行一次聚合
        select
        date_format(pay_time,'yyyy-MM-dd HH:mm') as pay_time
        ,sum(pay_gmv) as pay_gmv
        from tmp
        group by date_format(pay_time,'yyyy-MM-dd HH:mm')
    )t2
    on t1.minute_rn=t2.pay_time
)t1
;
02-08 17:19