Sql:日期的平均值

use*_*072 7 sql postgresql

我必须编写一个查询来计算每个客户购物之间的平均天数(不使用子查询).

    create table data {
customer varchar(20) not null,
bought date not null,
primary key (customer,bought)
}
Run Code Online (Sandbox Code Playgroud)

例如,

insert into data (customer,bought)
values (‘John Smith’, date ‘2011-02-01’),
(‘Alice Cooper’, date ‘2011-02-01’),
(‘Bob Baker’, date ‘2011-02-01’),
(‘John Smith’, date ‘2011-02-02’),
(‘Bob Baker’, date ‘2011-02-02’),
(‘Bob Baker’, date ‘2011-02-03’),
(‘Bob Baker’, date ‘2011-02-04’),
(‘Bob Baker’, date ‘2011-02-05’),
(‘Bob Baker’, date ‘2011-02-06’),
(‘Bob Baker’, date ‘2011-02-07’),
(‘John Smith’, date ‘2011-02-07’),
(‘Alice Cooper’, date ‘2011-02-08’);
Run Code Online (Sandbox Code Playgroud)

应该回答约翰史密斯等了1天然后5天,所以他的平均值是3天.Alice Cooper(!)等了7天,所以她的平均值是7.Bob Baker是每日跑步者,所以他的平均值是1.

我做过这样的事情

select distinct customer, avg (bought) as average from data;
Run Code Online (Sandbox Code Playgroud)

但它不起作用.

任何帮助将不胜感激.

小智 6

您必须以纪元秒为单位转换时间戳才能使用 avg 聚合函数:

SELECT
    customer,
    timestamp without time zone '1970-01-01' + cast(
       avg(EXTRACT(EPOCH FROM bought::timestamp)
    )::text as interval) 
FROM data
GROUP BY customer;
Run Code Online (Sandbox Code Playgroud)


Ric*_*iwi 2

链接答案的 PostgreSQL 版本

select customer, (max(bought) - min(bought)) / (count(bought)-1)
from data
group by customer;
Run Code Online (Sandbox Code Playgroud)