gpt4 book ai didi

sql - Postgresql中行之间的时间戳差异

转载 作者:行者123 更新时间:2023-11-29 13:35:13 25 4
gpt4 key购买 nike

在 PostgreSQL 中我有一个表

CREATE TABLE cubenotification.newnotification
(
idnewnotification serial NOT NULL,
contratto text,
idlocation numeric,
typology text,
idpost text,
iduser text,
idobject text,
idwhere text,
status text DEFAULT 'valid'::text,
data_crea timestamp with time zone DEFAULT now(),
username text,
usersocial text,
url text,
apikey text,
CONSTRAINT newnotification_pkey PRIMARY KEY (idnewnotification )
)

假设类型学字段可以是“owned_task”或“fwd_task”。我想从 DB 得到的是每对“idobject,iduser”类型为“fwd_task”的行的 data_crea 和类型为“owned_task”的行的 data_crea 之间严格以秒为单位的时间戳差异,我想也将 EXTRACT(WEEK FROM data_crea)) 获取为“周”,按“周”对结果进行分组。我的问题主要是关于在具有相同 idobject、相同 iduser 和不同类型的两行之间执行时间戳排序差异。

编辑:这里有一些示例数据

sample data

和 sqlfiddle 链接 http://sqlfiddle.com/#!12/6cd64/2

最佳答案

您正在寻找的是两个子选择的JOIN:

SELECT EXTRACT(WEEK FROM o.data_crea) AS owned_week
, iduser, idobject
, EXTRACT('epoch' FROM (o.data_crea - f.data_crea)) AS diff_in_sek
FROM (SELECT * FROM newnotification WHERE typology = 'owned_task') o
JOIN (SELECT * FROM newnotification WHERE typology = 'fwd_task') f
USING (iduser, idobject)
ORDER BY 1,4

->sqlfiddle

我按周和时间戳差异排序。周数基于“owned_task”的周数。

这假设每个 (iduser, idobject) 正好有 一个 行用于 'owned_task' 和一个用于 'fwd_task',而不是每周一次。您的规范留有解释的空间。

关于sql - Postgresql中行之间的时间戳差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14503788/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com