我有一张桌子tbltrans
transno | agent name | date|
--------+-----------+-------
1 01 | waw |2014-10-10|
1 02 | waw |2014-10-15|
1 03 | waw |2014-10-20|
1 04 | waw |2014-10-30|
我想查询postgresql来计算agentname的平均时间
结果如下:
agent name | average time|
--------+------------
waw | 5days |
我希望有人帮助我。 。 谢谢,更多的力量:)
答案 0 :(得分:0)
这样的事情:
select agent_name,
(max(date) - min(date)) / count(*) as average_days
from tbltrans
group by agent_name;
答案 1 :(得分:0)
这是解决方案:B - )
with diff(agent_name, values) as
(
select agent_name, date - lag(date,1,date) over (partition by agent_name order by date) from agents
)
select agent_name,
case when count(values) = 1 then '0 days'
else to_char(sum(values)::float / (count(values) - 1), '999.99') || ' days'
end
from diff
group by agent_name;
我在解决方案中使用了Windowing functions和Common table expressions