PostgreSQL:删除除最近日期之外的所有日期

时间:2016-05-23 15:35:09

标签: postgresql delete-row

我有一个像这样定义的表:

CREATE TABLE contracts (
  ContractID TEXT DEFAULT NULL,
  ContractName TEXT DEFAULT NULL,
  ContractEndDate TIMESTAMP WITHOUT TIME ZONE,
  ContractPOC TEXT DEFAULT NULL
);

在此表中,ContractID可能有多个记录,对于每个ContractID,我想删除所有记录,但是具有最新ContractEndDate的记录。我知道如何使用以下方法在MySQL中执行此操作:

DELETE contracts
  FROM contracts
  INNER JOIN (
    SELECT
      ContractID,
      ContractName,
      max(ContractEndDate) as lastDate,
      ContractPOC
    FROM contracts
    GROUP BY EmployeeID
    HAVING COUNT(*) > 0) Duplicate on Duplicate.ContractID = contracts.ContractID
    WHERE contracts.ContractEndDate < Duplicate.lastDate;

但我需要帮助才能在PostgreSQL中使用它。

1 个答案:

答案 0 :(得分:1)

你可以用这个

delete 
from 
    contracts c
using (SELECT
          ContractID,
          max(ContractEndDate) as lastDate
        FROM 
            contracts
        GROUP BY 
            ContractID) d
where
    d.ContractID = c.ContractID
    and c.ContractEndDate < d.lastDate;