如何获得间隔的绝对值 [英] How to get the absolute value of an interval

查看:123
本文介绍了如何获得间隔的绝对值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下语句:

 选择间隔'-1小时'

我不知道如何获取间隔的绝对值,即如果为负则切换或删除符号。我唯一想到的是以下内容:

  select abs(提取(从 -1小时开始的时间) )

但是我想知道是否有更优雅的方法(保留间隔类型的方法)?

解决方案

CASE 表达式看起来更不言自明。示例:

  SELECT 
i,
(当(i<间隔'0')时( -i)ELSE i END)AS abs_i

(值
(间隔'-2 h'),
(间隔'2 m')
)AS foo(i)

会产生:



<$我| abs_i
----------- + ----------
-02:00:00 | 02:00:00
00:02:00 | 00:02:00


Consider the following statement:

select interval '-1 hours'

I couldn't figure out how to get the absolute value of an interval, i.e. to toggle or remove the sign if negative. The only thing that came to my mind is the following:

select abs(extract(epoch from interval '-1 hours'))

But I wonder if there is a more elegant way (a way that preserves the interval type)?

解决方案

A CASE expression would look more self-explanatory. Example:

SELECT
    i,
    (CASE WHEN (i < INTERVAL '0') THEN (-i) ELSE i END) AS abs_i
FROM
    (VALUES
        (INTERVAL '-2 h'),
        (INTERVAL '2 m')
    ) AS foo (i)

which produces:

     i     |  abs_i
-----------+----------
 -02:00:00 | 02:00:00
 00:02:00  | 00:02:00

这篇关于如何获得间隔的绝对值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆