Postgresql

如果另一列為空,則獲取最低日期

  • March 11, 2019

我有以下

CREATE TABLE employees (employee_id int, from_date date, to_date date);

INSERT INTO employees(Employee_ID,From_Date,To_Date)
VALUES
   (1    ,       '1998-01-02'   ,  NULL),
   (1    ,       '2000-01-01'   ,  NULL),
   (1    ,       '2015-01-01'   ,  '2018-01-01'),
   (2    ,       '2005-01-01'   ,  '2006-01-01'),
   (2    ,       '2007-01-01'   ,  '2007-05-05'),
   (3    ,       '2002-02-02'   ,  '2004-02-02'),
   (3    ,       '2010-01-01'   ,  '2015-01-01'),
   (4    ,       '2001-01-01'   ,  '2005-03-03'),
   (4    ,       '2003-03-03'   ,  '2004-04-04');

僅當記錄具有To_Date並且該記錄的****From_DateTo_Date之間的持續時間小於三年時,我才想選擇 From_Date 最低的所有記錄**。**結果應如下所示:

Employee_ID     From_Date         To_Date
   2          2005-01-01       2006-01-01
   3          2002-02-02       2004-02-02

換句話說,如果任何員工在最低 From_Date 記錄中缺少 To_Date,並且如果 From_Date 最低的記錄有 To_Date 但 time_duration 超過 3 年,則不應考慮它們。從上面的結果表中可以看出,ID 為 1 的員工不被考慮,因為最低的 From_Date 記錄沒有 To_Date,ID 為 4 的員工不被考慮,因為最低記錄的 From_Date 和 To_Date 之間的持續時間超過三個年。

這是一個兩步問題:找到每個員工的 from_date 最低的行(也稱為“每個組的最大 n ”問題),然後過濾掉差異小於三年的行:

with emps as (
 select distinct on (employee_id) employee_id, from_date, to_date
 from employees
 where to_date is not null
 order by employee_id, from_date 
) 
select *
from emps
where to_date::timestamp - from_date::timestamp < interval '3 year';

線上範例:https ://rextester.com/QTLYEZ74319

這是我想出的

SELECT employee_id, from_date, to_date
FROM employees AS e1
WHERE to_date IS NOT NULL -- may not be useful as per comments.
 AND to_date - from_date <= (365 * 3)
 AND EXISTS (
   SELECT
   FROM employees AS e2
   WHERE e1.employee_id = e2.employee_id
   GROUP BY employee_id
   HAVING e1.from_date = min(e2.from_date)
 );

引用自:https://dba.stackexchange.com/questions/231804