【问题标题】:PostgreSQL query to breakdown interval into weeks, days, hours, minutes, secondsPostgreSQL 查询将间隔分解为周、天、小时、分钟、秒
【发布时间】:2021-05-14 15:45:11
【问题描述】:

我对 PostgreSQL 非常缺乏经验,我试图让一行返回从当前日期时间到给定日期时间的间隔,将周、天、小时、分钟和秒分解为单独的列。

除了一个非常复杂的解决方案之外,我得到的最接近的是:

SELECT

    (CURRENT_TIMESTAMP - '2021-01-01 00:00:00')::text AS str,
    
    SUBSTRING((CURRENT_TIMESTAMP - '2021-01-01 00:00:00')::text FROM  1 FOR 2)::NUMERIC AS days,
    SUBSTRING((CURRENT_TIMESTAMP - '2021-01-01 00:00:00')::text FROM  9 FOR 2)::NUMERIC AS hours,
    SUBSTRING((CURRENT_TIMESTAMP - '2021-01-01 00:00:00')::text FROM 12 FOR 2)::NUMERIC AS minutes,
    SUBSTRING((CURRENT_TIMESTAMP - '2021-01-01 00:00:00')::text FROM 15 FOR 2)::NUMERIC AS seconds

这让我很接近:

我的问题是:

  1. 此实现依赖于X days 子字符串中的字符数始终相同,但事实并非如此,那么如何使其更灵活?
  2. 我可以将(CURRENT_TIMESTAMP - '2021-01-01 00:00:00')::text 的结果保存到一个简单的变量中,这样我就不必重复了吗?
  3. 如何添加“周”列并获取 5 weeks, 5 days, ... 而不是 40 days

我看过https://stackoverflow.com/a/56776697/2909854,但我不想几个月。

如果我可以将每个结果的输出保存到一个变量中,我可以像这样做一些相对干净的事情:https://stackoverflow.com/a/21323783/2909854

感谢任何帮助。谢谢!

【问题讨论】:

    标签: sql postgresql intervals


    【解决方案1】:

    你可以使用extract()

    SELECT  (CURRENT_TIMESTAMP - '2021-01-01 00:00:00')::text AS str,
            extract(day from CURRENT_TIMESTAMP - '2021-01-01 00:00:00')as days,
            extract(hour from CURRENT_TIMESTAMP - '2021-01-01 00:00:00')as hours,
            extract(minute from CURRENT_TIMESTAMP - '2021-01-01 00:00:00')as minutes,
            extract(second from CURRENT_TIMESTAMP - '2021-01-01 00:00:00')as seconds;
    

    为避免重复表达式,您可以使用common table expression

    with input (duration) as (
      values (CURRENT_TIMESTAMP - '2021-01-01 00:00:00')
    )
    select duration::text as str,
           extract(day from duration) as days, 
           extract(hour from duration) as hours,
           extract(minute from duration) as minutes,
           extract(second from duration) as seconds
    from input;
    

    您无法从间隔中获取“周”,但您可以使用 justify_interval() 转换天数 to months

    【讨论】:

    • 太好了,这肯定解决了#1。 #2 或 #3 有什么想法吗?谢谢!
    猜你喜欢
    • 2019-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-06
    相关资源
    最近更新 更多