11

我正在开发一个 Postgres 8.3 数据库。我使用的查询旨在仅选择工作日中包含的行。现在我已经像下面的示例中那样手动执行此操作,但我想将其转移到一些功能,我可以在其中指定开始和结束日期并获得相同的逻辑来应用如下。那是

如何创建一个输入为开始日期和结束日期的函数,该函数的结果将是选择仅包含在数据集的工作日中的所有行(我想排除每个 staurday 和 sunday 作为 where 子句条件以下)?

create table filter_tbl as
select *
from base_tbl  where
(start_Time >= '2012-11-5' and start_Time < '2012-11-10')
or (start_time >= '2012-11-12' and start_time < '2012-11-17')
or (start_time >= '2012-11-19' and start_time < '2012-11-24')
or (start_time >= '2012-11-26' and start_time < '2012-12-01')
or (start_time >= '2012-12-03' and start_time < '2012-12-07')
or (start_time >= '2012-12-10' and start_time < '2012-12-14')
or (start_time >= '2012-12-17' and start_time < '2012-12-21')
or (start_time >= '2012-12-24' and start_time < '2012-12-28')
or (start_time >= '2012-12-31' and start_time < '2013-01-04')
or (start_time >= '2013-01-07' and start_time < '2013-01-11')
or (start_time >= '2013-01-14' and start_time < '2013-01-18')
or (start_time >= '2013-01-21' and start_time < '2013-01-25')
or (start_time >= '2013-01-28' and start_time < '2013-02-02')
or (start_time >= '2013-02-04' and start_time < '2013-02-09')
or (start_time >= '2013-02-11' and start_time < '2013-02-16')
or (start_time >= '2013-02-18' and start_time < '2013-02-23')
or (start_time >= '2013-02-25' and start_time < '2013-03-02')
or (start_time >= '2013-03-04' and start_time < '2013-03-09')
or (start_time >= '2013-03-11' and start_time < '2013-03-16');
4

5 回答 5

19

根据您的示例,这似乎start_time是文本。然后您需要将其转换为timestampusing to_timestamp,然后使用EXTRACT.

您的WHERE条款将是这样的:

WHERE EXTRACT(dow FROM timestamp (to_timestamp(start_time, "YYYY-MM-DD"))
NOT IN (0,6)

链接:数据类型格式化函数日期/时间函数和运算符

于 2013-03-04T21:13:15.633 回答
8
select *
from base_tbl  
where extract(dow from start_time) in (1,2,3,4,5)
于 2013-03-04T21:01:32.277 回答
1

检查日期时间功能

例如

SELECT EXTRACT(DOW FROM TIMESTAMP '2001-02-16 20:38:40');

返回5,代表Friday

于 2013-03-04T21:01:19.637 回答
1

以下应返回星期几。

date_part('dow', Date);

默认设置 0 是星期日,6 是星期六

于 2013-03-04T21:01:32.210 回答
1
select to_char(date, 'Day') from table
于 2015-07-17T11:00:50.763 回答