Valerio Marcellino
Valerio Marcellino

Reputation: 308

Timestamp difference between rows in Postgresql

In PostgreSQL I have a table

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 )
)

Let's say that typology field can be "owned_task" or "fwd_task". What I'd like to get from DB is the timestamp difference in seconds strictly between data_crea of the row with typology "fwd_task" and data_crea of the row with typology "owned_task" for every couple "idobject,iduser", and I'd like to get also the EXTRACT(WEEK FROM data_crea)) as "weeks", grouping the results by "weeks". My problem is principally about performing the timestamp ordered difference between two rows with same idobject, same iduser and different typology.

EDIT: Here some sample data

sample data

and sqlfiddle link http://sqlfiddle.com/#!12/6cd64/2

Upvotes: 1

Views: 1722

Answers (1)

Erwin Brandstetter
Erwin Brandstetter

Reputation: 658707

What you are looking for is the JOIN of two subselects:

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

I order by week and timestamp difference. The week number is based on the week of 'owned_task'.

This assumes there is exactly one row for 'owned_task' and one for 'fwd_task' per (iduser, idobject), not one per week. Your specification leaves room for interpretation.

Upvotes: 2

Related Questions