[英]Using datediff in subquery to calculate historic age
I'm trying to generate a view on open orders of an online store.我正在尝试生成有关在线商店的未结订单的视图。 I have a table with all orders and their respective dates (created_date, closed_cate), all of them are closed today.
我有一个包含所有订单及其各自日期(created_date,closed_cate)的表格,所有订单今天都关闭。
In a first step I want to calculate the average age of open orders for any given day:第一步,我想计算任何给定日期的未结订单的平均年龄:
select
c.DATE,
(SELECT avg(datediff('days', ord.ORDER_DATE, c.DATE))
FROM "Orders" ord
WHERE c.DATE>=ord.ORDER_DATE AND c.DATE<=ord.Order_close_date
)
FROM CALENDAR c
WHERE c.DATE<=CURRENT_DATE()
ORDER BY c.DATE desc
When executing this I'll receive an error code: "SQL compilation error: Unsupported subquery type cannot be evaluated"执行此操作时,我将收到错误代码: “SQL 编译错误:无法评估不受支持的子查询类型”
Is there any way to solve this?有没有办法解决这个问题? The result should be an average for each day.
结果应该是每天的平均值。 Any input is highly appreciated!
任何输入都受到高度赞赏!
One method is a recursive CTE:一种方法是递归 CTE:
with cte as (
select o.order_date as dte, o.order_close_date, 0 as days_aging
from "Orders" o
union all
select o.order_date + interval '1 day', o.order_close_date, days_aging + 1
from cte
where dte < o.order_close_date
)
select dte, avg(days_aging)
from cte
group by dte;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.