希望为两种客户类型计算两列之间的分钟数,其中start_time和end_time作为时间戳,不带zone,然后对每种结果求平均值。
我尝试使用extract()通过使用以下语句,但不能得到正确的结果:
select avg(duration_minutes)
from (
select started_at,ended_at, extract('minute' from (started_at - ended_at)) as duration_minutes
from my_data
where customer_type = 'member'
) avg_duration;
结果:
<表类>avg tbody><<tr>0.000 表类>
extract(minute from ...)
用间隔中的分钟提取字段。如果间隔时间是1小时26分45秒结果将是26
而不是86。
要将间隔转换为等效的分钟数,请使用extract(epoch ...)
提取总秒数并将其乘以60。
select avg(duration_minutes)
from (
select started_at,
ended_at,
extract(epoch from (started_at - ended_at)) * 60 as duration_minutes
from my_data
where customer_type = 'member'
) avg_duration;
请注意,您可以计算间隔的平均值,而不需要将其转换为分钟:
select avg(duration)
from (
select started_at,
ended_at,
started_at - ended_at as duration
from my_data
where customer_type = 'member'
) avg_duration;
根据您如何使用结果,返回interval
可能更有用。您还可以使用将转换为分钟:
extract(epoch from avg(duration)) * 60 as average_minutes