代码之家  ›  专栏  ›  技术社区  ›  John

PostgreSQL按日期筛选条目,但包含日期为空的遗漏条目

  •  0
  • John  · 技术社区  · 6 年前

    假设我有一个简单的表,例如:

    CREATE TABLE public.test
    (
        id integer NOT NULL,
        d date NOT NULL
    )
    

    有数据:

    insert into test values(1, '2018-09-05'::date);
    insert into test values(2, '2018-08-05'::date);
    insert into test values(2, '2018-07-05'::date);
    

    我怎么可能,以最简单的方式,得到这两个条目的日期是 不符合日期筛选条件的记录? 例如。

    select id, d from
    test where d > '2018-09-01'
    union
    select id, d from test;
    

     2  "2018-07-05"
     2  "2018-08-05"
     1  "2018-09-05"
    

    我想:

    2   "null"
    1   "2018-09-05"
    

    不能在整个联合体中使用distinct,这并没有帮助。 我也许应该加入这个表本身,做些什么,但我不知道什么。

    2 回复  |  直到 6 年前
        1
  •  2
  •   Michel Milezzi    6 年前

    SELECT 
        DISTINCT
        id, 
        (case when d > '2018-09-01' then d end) as d 
    FROM 
        test 
    
        2
  •  1
  •   randomDude1001    6 年前

    我的解决方案:

    select distinct 
      t.id,
      (select max(t_max.d) from test t_max where t_max.id = t.id and t_max.d > '2018-09-01')
    from test t;
    

    你可以测试一下 here .