postgresql 一个需求:围绕两个字段时间差得到时分秒格式

   日期:2020-07-11     浏览:155    评论:0    
核心提示:初步sql,思路是先获取两个时间差的秒数,再相除获取时间和分钟缺点是没有考虑负时间select case when char_length(trunc(a.between_sec/a.hour_sec)::varchar ) <=2 then lpad(trunc(a.between_sec/a.hour_sec)::varchar,2,0) else trunc(a.between_sec/a.hour_sec)::varchar

初步sql,思路是先获取两个时间差的秒数,再相除获取时钟和分钟
(没有考虑负时间)

select case when char_length(trunc(a.between_sec/a.hour_sec)::varchar ) <=2 
                 then lpad(trunc(a.between_sec/a.hour_sec)::varchar,2,'0')
		    else trunc(a.between_sec/a.hour_sec)::varchar
        end||':'||
        lpad(trunc((a.between_sec-trunc(a.between_sec/a.hour_sec)*a.hour_sec)/a.min_sec)::varchar,2,'0') || ':' ||
		lpad((a.between_sec - trunc(a.between_sec/a.hour_sec) * a.hour_sec - trunc((a.between_sec-trunc(a.between_sec/a.hour_sec)*a.hour_sec)/a.min_sec)*a.min_sec)::varchar,2,'0')
 from ( select extract(epoch FROM (now() - (now()-interval '2.11 day') )) as between_sec,
			   60*60 as hour_sec,
		       60    as min_sec
      ) a;
			

优化后的sql如下(同时考虑到了负时间)

select case when (extract(day FROM ( a.bet ))*a.day_hour + extract(hour FROM ( a.bet )) ) < 0
				  and (extract(day FROM ( a.bet ))*a.day_hour + extract(hour FROM ( a.bet )) ) >= -9
				  then  '-0'||abs( (extract(day FROM ( a.bet ))*a.day_hour + extract(hour FROM ( a.bet )) ) )::varchar
			when (extract(day FROM ( a.bet ))*a.day_hour + extract(hour FROM ( a.bet )) ) >= 0
				  and (extract(day FROM ( a.bet ))*a.day_hour + extract(hour FROM ( a.bet )) ) <= 9
		    	  then  '0'||(extract(day FROM ( a.bet ))*a.day_hour + extract(hour FROM ( a.bet )) )::varchar	
			else (extract(day FROM ( a.bet ))*a.day_hour + extract(hour FROM ( a.bet )) )::varchar		 
        end || ':' ||
       case when extract(minute FROM ( a.bet )) < 0 and extract(minute FROM ( a.bet )) >= -9
			     then '-0'||abs(extract(minute FROM ( a.bet )))::varchar
			when extract(minute FROM ( a.bet )) >=0 and extract(minute FROM ( a.bet )) <= 9
			     then '0'||(extract(minute FROM ( a.bet ))::varchar)
			else extract(minute FROM ( a.bet ))::varchar
		end || ':' ||
	    case when extract(second FROM ( a.bet )) < 0 and extract(second FROM ( a.bet )) >= -9
	              then '-0'||abs(extract(second FROM ( a.bet )))::varchar
			 when extract(second FROM ( a.bet )) >=0 and extract(second FROM ( a.bet )) <= 9
				  then '0'||(extract(second FROM ( a.bet ))::varchar)
			 else extract(second FROM ( a.bet ))::varchar
		 end as between_str 
  from ( select (now() - (now()-interval '2.11 day') ) as bet,
				24     as day_hour,
				60*60  as hour_sec,
				60     as min_sec
	      ) a;

 
打赏
 本文转载自:网络 
所有权利归属于原作者,如文章来源标示错误或侵犯了您的权利请联系微信13520258486
更多>最近资讯中心
更多>最新资讯中心
0相关评论

推荐图文
推荐资讯中心
点击排行
最新信息
新手指南
采购商服务
供应商服务
交易安全
关注我们
手机网站:
新浪微博:
微信关注:

13520258486

周一至周五 9:00-18:00
(其他时间联系在线客服)

24小时在线客服