Sql:日期的平均值

时间:2011-03-14 21:20:35

标签: sql postgresql

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

    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天。 Alice Cooper(!)等了7天所以她 平均是7.鲍勃贝克是每日跑步者,所以他的平均值是1。

我做过类似的事情

select distinct customer, avg (bought) as average from data;

但它不起作用。

非常感谢任何帮助。

6 个答案:

答案 0 :(得分:4)

您必须在epoch秒内转换时间戳才能使用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;

答案 1 :(得分:2)

PostgreSQL版本的链接答案

select customer, (max(bought) - min(bought)) / (count(bought)-1)
from data
group by customer;

答案 2 :(得分:2)

这在类似的情况下对我有用:

SELECT customer, avg(AGE(now(),bought)) as waited
FROM data 
GROUP BY customer

答案 3 :(得分:2)

选择max-min / count不是平均值。尝试:

 timestamp 'epoch' + avg(date_part(epoch, date_column))  * interval '1 second' 

答案 4 :(得分:1)

您可能希望使用分组声明

select 
   customer, 
   datediff(D, min(bought), max(bought)) / count(bought) as average
from data
group by customer

如果选择列表中有聚合函数,则必须对非聚合成员的其他字段使用分组。

这是在SQL Server上测试的,语法可能与Postgresql不同,后者我没有使用。

答案 5 :(得分:-4)

SELECT customer, AVG(bought) AS average FROM data GROUP BY customer