很多报表里面都会有人均使用时长
这个概念,来统计用户使用app的深度。
通常我们说的人均使用时长
就是拿总使用时长除以总使用人数,除完的结果是秒。
这种秒的结果在页面上就很不直观了。
那我们就会把秒格式化为:12782-->03:33:02
我们来看看这种结果怎么处理,其实这种处理和数字有几个100,几个10,几个1是一样的
1.取小时数据,这个时候我们要取整floor(12782/3600)
,并且做判断是一位数还是两位数,如果是一位数我们得在前面补一下“0”,并在后面拼接一个“:”,如果是两位数就在后面拼接一个“:”,如果没有够小时就拼接一个“00:”(下面的分和秒也一样)
case when length(floor(12782/3600))=1 then concat('0',floor(12782/3600),':')
when length(floor(12782/3600))=2 then concat(floor(12782/3600),':')
else '00:' end
2.取分钟数据,分钟数据是除完小时(3600)后的余数,再除60取整数floor(12782%3600/60)
case when length(floor(12782%3600/60))=1 then concat('0',floor(12782%3600/60),':')
when length(floor(12782%3600/60))=2 then concat(floor(12782%3600/60),':')
else '00:' end
3.最后是秒数,取完小时再取完分钟后的余数floor(12782%3600%60)
case when length(floor(12782%3600%60))=1 then concat('0',floor(12782%3600%60))
when length(floor(12782%3600%60))=2 then floor(12782%3600%60)
else '00' end
我们来看一下整体的结果:
spark-sql> select
> concat(
> case when length(floor(12782/3600))=1 then concat('0',floor(12782/3600),':')
> when length(floor(12782/3600))=2 then concat(floor(12782/3600),':')
> else '00:' end,
> case when length(floor(12782%3600/60))=1 then concat('0',floor(12782%3600/60),':')
> when length(floor(12782%3600/60))=2 then concat(floor(12782%3600/60),':')
> else '00:' end,
> case when length(floor(12782%3600%60))=1 then concat('0',floor(12782%3600%60))
> when length(floor(12782%3600%60))=2 then floor(12782%3600%60)
> else '00' end
> );
03:33:02
Time taken: 0.364 seconds, Fetched 1 row(s)
spark-sql> select
> concat(
> case when length(floor(127820/3600))=1 then concat('0',floor(127820/3600),':')
> when length(floor(127820/3600))=2 then concat(floor(127820/3600),':')
> else '00:' end,
> case when length(floor(127820%3600/60))=1 then concat('0',floor(127820%3600/60),':')
> when length(floor(127820%3600/60))=2 then concat(floor(127820%3600/60),':')
> else '00:' end,
> case when length(floor(127820%3600%60))=1 then concat('0',floor(127820%3600%60))
> when length(floor(127820%3600%60))=2 then floor(127820%3600%60)
> else '00' end
> )
> ;
35:30:20
Time taken: 0.367 seconds, Fetched 1 row(s)