计算平均年龄但在 postgres 中得到不正确结果的问题

Issues with calculating average age but getting incorrect results in postgres

我正在获取帐户的平均年龄。为此,我使用了以下代码。

select 
  m."storeId", s."locationName",
  COUNT(m."membershipEnded" is not null) as "Cancelations",
  AVG(AGE(m."membershipEnded"::date, m."memberSince"::date)) as "Membership Duration in days"
FROM "members" m
INNER JOIN "stores" s on s."storeId" = m."storeId"
where (m."membershipEnded" is not null 
  and m."membershipEnded"::date > m."memberSince"::date)  
  and "memberSince" is not null 
  and f."countryCode" in ('US','CA') 
  and s."storeStatus" ='Active'
group by 1,2
order by "storeId";

我得到的结果包括无效天数,因此一个示例是:“1 年 35 天 22:17:08.546743”或另一个“2 年 9 月 41 天 13:42:51.453257 ".

我到处找,终于找到了这个误算天数的原因。

我们将不胜感激。

我还要注意,我刚刚减去两者以获得天数差异,但我更喜欢年、月和日的结果,就像年龄一样。

Postgresql 版本为 10.9

***** 编辑 - 回答 更新后的代码和下面的答案:

justify_interval() 非常有效

select 
  m."storeId", s."locationName",
  COUNT(m."membershipEnded" is not null) as "Cancelations",
  justify_interval(AVG(AGE(m."membershipEnded"::date, m."memberSince"::date))) as "Membership Duration in days"
FROM "members" m
INNER JOIN "stores" s on s."storeId" = m."storeId"
where (m."membershipEnded" is not null 
  and m."membershipEnded"::date > m."memberSince"::date)  
  and "memberSince" is not null 
  and s."countryCode" in ('US','CA') 
  and s."storeStatus" ='Active'
group by 1,2
order by "storeId";

间隔操作可能会导致此类结果,因为操作是针对年、月、日等进行的。

克服它,使用justify_interval调整超过months/days/hours等

select justify_interval('1 year 35 days 22:17:08.546743'), 
       justify_interval('2 years 9 mons 41 days 13:42:51.453257');
          justify_interval           |            justify_interval
-------------------------------------+-----------------------------------------
 1 year 1 mon 5 days 22:17:08.546743 | 2 years 10 mons 11 days 13:42:51.453257