简体   繁体   English

计算PostgreSQL数据库中的平均日期

[英]Calculate average date in PostgreSQL db

I have a table in PostgreSQL which has orders purchased at various dates. 我在PostgreSQL中有一张表,该表有在不同日期购买的订单。 In order to archive the data we need to merge all the records of the year and merge it into one record with a average purchase date calculated based on the purchase dates. 为了存档数据,我们需要合并一年中的所有记录并将其合并为一条记录,并根据购买日期计算出平均购买日期。

How do I calculate the average purchase date in PostgreSQL? 如何计算PostgreSQL中的平均购买日期? Or Is there a way to do it in JAVA? 还是有办法在JAVA中做到这一点?

Since your dates are all in the same year, you could use extract to convert the dates to a day-of-year, average those numbers, and then add that back to the first day of the year to get a date: 由于您的日期都在同一年,因此您可以使用extract将日期转换为一年中的某天,然后将这些数字取平均值,然后将其添加回该年的第一天以获取日期:

select '2015-01-01'::date
     + avg(extract(doy from whatever_your_date_column_is))::int
     - 1
from ...

You need the ::int cast because avg gives you a double precision value but there is no operator for adding doubles to dates; 您需要::int强制转换,因为avg为您提供双精度值,但没有用于将双精度加到日期的运算符; the -1 adjustment is needed because the day-of-year values are one-based rather than zero-based. 需要-1调整,因为一年中的日期值是基于1的,而不是基于0的。 Note that adding an integer to a date simply adds that many days. 请注意, 将整数添加到日期只会增加很多天。

You would, of course, adjust the '2015-01-01' to match whatever year you're working with. 当然,您可以调整'2015-01-01'以匹配您使用的年份。

You should convert your dates to an epoch (seconds since 1970-01-01 00:00:00), take the average of that, then turn the result back into a date: 您应该将日期转换为一个epoch (自1970-01-01 00:00:00以来的秒数),取其平均值,然后将结果转换为日期:

SELECT extract(year from purchase_date) AS year_of_purchase,
       to_timestamp(avg(extract(epoch from purchase_date)))::date AS avg_purchase_date
FROM orders
GROUP BY 1;

Add other fields and filters as required. 根据需要添加其他字段和过滤器。

java.time java.time

In java.time , if you want the average date within a timeframe of the calendar year you could use the ZonedDateTime class and it's getDayOfYear method. java.time中 ,如果希望在日历年的时间范围内获得平均日期,则可以使用ZonedDateTime类,它是getDayOfYear方法。

For a timeframe beyond the calendar year, you could choose a point in the past. 对于日历年以外的时间范围,您可以选择过去的时间点。 I suggest the Java epoch of first moment of 1970 in UTC. 我建议在UTC的1970年第一刻的Java时代。 See the constant ZoneOffset.UTC . 参见常量ZoneOffset.UTC Search StackOverflow to learn how to get the number of days from that early pint to each of your date-time instances. 搜索StackOverflow以了解如何获取从该早期品脱到每个日期时间实例的天数。 Average those numbers of days to arrive at your average date. 平均得出您的平均日期所需的天数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM