如何在PostgreSQL中获取星期开始日期和结束日期字符串? [英] How to get week start and end date string in PostgreSQL?

查看:183
本文介绍了如何在PostgreSQL中获取星期开始日期和结束日期字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 PostgreSQL 8.3 。我有一个这样的表:

I am using PostgreSQL 8.3. I have a table like this:

id        regist_time        result
-----------------------------------
1     2012-07-09 15:00:08      3
2     2012-07-25 22:24:22      7
4     2012-07-07 22:24:22      8

regist_time 的数据类型为 timestamp

I我需要找到一个星期的时间间隔(开始到结束)
和sum(result)作为数字。

I need to find a week time interval(start to end) and sum(result) as num.

我想得到的结果是:

      week                    num    
---------------------------------
7/1/2012-7/7/2012              10
7/8/2012-7/14/2012              5
7/15/2012-7/21/2012             3
7/22/2012-7/28/2012            11

我可以在今年获得星期几:

I can get the week number just in this year:

SELECT id,regis_time, EXTRACT(WEEK FROM regis_time) AS regweek
FROM tba

关键部分是

EXTRACT(WEEK FROM regis_time) 

提取函数只能获取星期数在今年,我如何开始在一周内的开始时间?

extract function can only get the week number in this year, how can I get start time to end time in one week?

推荐答案

您可以使用 date_trunc('week',...)

You can use date_trunc('week', ...).

例如:

SELECT date_trunc('week', '2012-07-25 22:24:22'::timestamp);
-> 2012-07-23 00:00:00

然后,您可以将其转换为日期,如果您对开始时间不感兴趣。

Then, you can convert this into a date, if you're not interested in a start time.

也要获取结束日期:

SELECT    date_trunc('week', '2012-07-25 22:24:22'::timestamp)::date
   || ' '
   || (date_trunc('week', '2012-07-25 22:24:22'::timestamp)+ '6 days'::interval)::date;

-> 2012-07-23 2012-07-29

(我在这里使用了默认格式,当然可以修改它以使用MM / DD / YYYY。)

(I've used the default formatting here, you can of course adapt this to use MM/DD/YYYY.)

请注意,如果要对时间戳进行比较,请不要使用 (date_trunc('week',...)+'6 days':: interval ,您可能要添加整整一周,并对一周结束使用严格的比较。

Note that, if you want to make comparisons on timestamps, instead of using (date_trunc('week', ...) + '6 days'::interval, you might want to add an entire week and use a strict comparison for the end of the week.

这将排除一周最后一天的 y 时间戳(因为截止时间是当天的午夜) 。

This will exclude y timestamps on the last day of the week (since the cut-off time is midnight on the day).

    date_trunc('week', x)::date <= y::timestamp
AND y::timestamp <= (date_trunc('week', x) + '6 days'::interval)::date

这将包括它们:

    date_trunc('week', x)::date <= y::timestamp
AND y::timestamp < (date_trunc('week', x) + '1 week'::interval)

(在极少数情况下,您不能在<$上使用 date_trunc c $ c> y 。)

(That's in the rare cases when you can't use date_trunc on y directly.)

如果您的星期从星期日开始,请替换 date_trunc('week',x):: date date_trunc('week',x +'1 day':: interval):: date -'1天'::间隔应该有效。

If your week starts on a Sunday, replacing date_trunc('week', x)::date with date_trunc('week', x + '1 day'::interval)::date - '1 day'::interval should work.

这篇关于如何在PostgreSQL中获取星期开始日期和结束日期字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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