我必须编写一个查询来计算每个客户购物之间的平均天数(不使用子查询)。
create table data {
customer varchar(20) not null,
bought date not null,
primary key (customer,bought)
}
例如,
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’);
应该返回 John Smith 等了 1 天然后等了 5 天,所以他的平均时间是 3 天。爱丽丝库珀(!)等了 7 天,所以她 平均值是 7。Bob Baker 是一名日常运行者,所以他的平均值是 1。
我做过这样的事
select distinct customer, avg (bought) as average from data;
但它不起作用。
任何帮助将不胜感激。
最佳答案
您必须将时间戳转换为纪元秒才能使用 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;
关于Sql:一个日期的平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5304696/