Sql:日期的平均值
我必须编写一个查询来计算每个客户购物之间的平均天数(不使用子查询)。
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;
但它不起作用。
任何帮助将不胜感激。
I have to write a query to calculate the average number days between the shopping for each customer (without using subqueries).
create table data {
customer varchar(20) not null,
bought date not null,
primary key (customer,bought)
}
For example,
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’);
should return that John Smith waited 1 day then 5 days, so his average is 3 days. Alice Cooper(!) waited 7 days so her
average is 7. Bob Baker is a daily runner so his average is 1.
I have done something like this:
select distinct customer, avg (bought) as average from data;
but it doesn't work.
Any help will be greatly appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您必须以纪元秒为单位转换时间戳才能使用 avg 聚合函数:
You have to convert your timestamp in epoch seconds to use avg aggregate function :
PostgreSQL 版本的链接答案
PostgreSQL version of the linked answer
这在类似的情况下对我有用:
This worked for me in similar situation:
选择最大-最小/计数不是平均值。尝试:
selecting max-min/count is NOT the average. try:
您可能想要使用 group by 语句
每当选择列表中有一个聚合函数时,您必须对不属于聚合成员的其他字段使用分组。
这是在 SQL Server 上测试的,语法可能与我没有使用的 Postgresql 不同。
You might want to use a group by statement
Whenever you have an aggregate function in the select list, you have to use grouping on the other fields that are not members of the aggregation.
This was tested on SQL Server and the syntax may differ to Postgresql, which I am not using.