PostgresQL - 报告的第一次和最后一次修订之间的时间差异

时间:2013-06-01 09:40:01

标签: postgresql

我的report_history表的表结构如下:

CREATE TABLE "report_history"(
"pk"                 SERIAL          PRIMARY KEY,
"revision"           BIGINT,
"report_fk"          BIGINT,
"old_status_fk"      BIGINT,
"updatedby_fk"       BIGINT,
"updated_datetime"   TIMESTAMP,
"file_path"          TEXT,
"synopsis"           TEXT
);

虽然report表本身的定义如下:

CREATE TABLE "report"(
"pk"                    SERIAL          PRIMARY KEY,
"report_uuid"           VARCHAR(32)     UNIQUE,
"study_fk"              BIGINT,
"status_fk"             BIGINT,
"priority_fk"           BIGINT,
"report_relative_path"  VARCHAR(256),
"report_type_fk"        BIGINT,
"createdby_fk"          BIGINT,
"created_datetime"      TIMESTAMP
);

我想知道的是如何找到报告第一次修订与同一报告最后修订之间的差异(及时)?为了澄清,在pesudocode中,我想执行以下减法:

RETURN report_history.updated_datetime (newest) - report_history.updated_datetime
(oldest) WHERE report_fk = ?

任何人都可以帮我解决这个问题吗?提前谢谢。

1 个答案:

答案 0 :(得分:0)

你的问题非常含糊不清,但这样的事情可能会让你开始:

select r.*, rh.max_updated, rh.min_updated
from report as r
  join (
     select report_fk, 
            min(updated_datetime) as min_updated,
            max(updated_datetime) as max_updated
     from report_history
     group by report_fk
  ) as rh on rh.report_fk = r.pk;