PostgreSQL 查询将间隔细分为周、天、小时、分钟、秒

问题描述

我对 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

这让我很接近:

enter image description here

我的问题是:

  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

感谢任何帮助。谢谢!

解决方法

您可以使用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