20

大家好 ,我的 pg admin 数据库中有一个表。这个表中有一个员工表。有这个字段:- 1)name 2)date_of_birth

现在的情况是我想知道当前日期和即将到来的 20 天的生日例如,如果当前日期是 2013 年 1 月 28 日,那么

1)from_date=28-Jan-2013
2)to_date=16-feb-2013

我想从 date_of_birth的表中选择所有记录

lies between 28-Jan and 16-feb
4

3 回答 3

40

尝试这个:

SELECT *
FROM   bdaytable
WHERE  bdate >= '2013-01-28'::DATE
AND    bdate <= '2013-02-16'::DATE;

您也可以尝试overlaps

SELECT *
FROM bdaytable
WHERE (bdate, bdate) 
OVERLAPS ('2013-01-28'::DATE, '2013-02-16'::DATE);

, extract,monthday : _

SELECT *
FROM   bdaytable
WHERE  Extract(month from bdate) >= Extract(month from '2013-01-28'::DATE)
AND    Extract(month from bdate) <= Extract(month from '2013-02-16'::DATE)
AND    Extract(day from bdate) >= Extract(day from '2013-01-28'::DATE)
AND    Extract(day from bdate) <= Extract(day from '2013-02-16'::DATE);

合并Now()interval使用当前日期使查询动态化:

SELECT *
FROM   bdaytable
WHERE  Extract(month from bdate) >= Extract(month from Now())
AND    Extract(month from bdate) <= Extract(month from Now() + Interval '20 day')
AND    Extract(day from bdate) >= Extract(day from Now())
AND    Extract(day from bdate) <= Extract(day from Now() + Interval '20 day');
于 2013-01-29T19:22:11.800 回答
3
select *
from employee
where 
    to_char(date_of_birth, 'MMDD') between 
    to_char(current_date, 'MMDD') and to_char(current_date + 20, 'MMDD')
于 2013-01-29T21:45:14.363 回答
0

我认为这应该有效。使用interval.

SELECT * 
FROM Employee
WHERE Date_Of_Birth >= now() AND Date_Of_Birth <= now() + interval '20 day'

如果您想获得这几天之间的任何出生日期(年份无关紧要),那么情况会略有不同。

编辑

如果年份无关紧要,虽然我确信有更好的方法,但这可能会奏效。基本上它只是将所有年份转换为普通年份(在本例中为 2000 年)——您也可以对输入参数执行相同操作。

(Date_Of_Birth + (2000-EXTRACT(YEAR FROM Date_Of_Birth) || ' years')::interval)

好奇其他人过去使用了什么,因为这可能不是最有效的。

祝你好运。

于 2013-01-29T19:22:08.043 回答