PostgreSQL query where date oldest

别说谁变了你拦得住时间么 提交于 2019-12-12 00:50:40

问题


I have a table in Postgres called calendar and I am trying to query the first date value stored where year=2013.

I have written the following query which works, however I am wondering if I can query the first date instead of just getting all data and limiting just to one?

SELECT date FROM calendar WHERE year=2013 ORDER BY date ASC LIMIT 1

回答1:


        -- the schema
DROP SCHEMA lutser CASCADE;
CREATE SCHEMA lutser;
SET search_path='lutser';

        -- the table
CREATE TABLE years
  ( zdate DATE NOT NULL PRIMARY KEY
  -- omitting a separate "year" field
  -- , since it can be derived from a date.
  -- ... ...
  );
        -- the data
INSERT INTO years(zdate)
SELECT gs
FROM generate_series( '2012-1-1' , '2014-12-31', '7 days'::interval) gs
        ;

        -- the query
SELECT zdate
FROM years yy
WHERE date_trunc( 'year' , yy.zdate) = '2014-01-01'::date
AND NOT EXISTS (
        SELECT *
        FROM years nx
        WHERE  date_trunc( 'year' , nx.zdate) = '2014-01-01'::date
        AND nx.zdate < yy.zdate
        )
        ;

        -- the same query using a CTE
WITH this AS (
        SELECT zdate
        FROM years yy
        WHERE date_trunc( 'year' , yy.zdate) = '2014-01-01'::date
        )
SELECT th.zdate
FROM this th
WHERE NOT EXISTS (
        SELECT *
        FROM this nx
        WHERE nx.zdate < th.zdate
        )
        ;


\q
        -- the result
DROP SCHEMA
CREATE SCHEMA
SET
CREATE TABLE
INSERT 0 157
   zdate
------------
 2014-01-05
(1 row)



回答2:


Have you tried simply something like this?

Case if you have a year field:

select MIN(date)
from calendar
where year = 2013

Case if you haven't a year field:

select MIN(date)
from calendar
where date >= '01-01-2013'


来源:https://stackoverflow.com/questions/21203246/postgresql-query-where-date-oldest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!