PostgreSQL返回精确或最接近查询日期的日期 [英] PostgreSQL return exact or closest date to queried date

查看:90
本文介绍了PostgreSQL返回精确或最接近查询日期的日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下postgresql语法,它们返回值,其中session_date匹配$ date_string

I have the following postgresql syntax that returns values WHERE session_date matches $date_string

问题是有时$ date_string在表中不可用,所以我希望将最接近的日期返回到$ date_string

Problem is that sometimes the $date_string will not be available in the table, so I am looking to return the closest date to the $date_string

$date_string = '2014-04-25';

SELECT year, session_date FROM calendar_dates WHERE session_date='$date_string'

有什么想法可以做到吗?

Any ideas how I can do this?

推荐答案

如果您想要最近的日期,可以这样:

If you want the closest date before, do it this way:

SELECT year, session_date
FROM calendar_dates
WHERE session_date < '$date_string'
ORDER BY session_date DESC
LIMIT 1;

之后的最近日期使用类似的逻辑。

The closest date after uses similar logic.

对于最接近的一方:

SELECT year, session_date
FROM calendar_dates
ORDER BY abs(session_date - date '$date_string') 
LIMIT 1;

这篇关于PostgreSQL返回精确或最接近查询日期的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆