从具有不同合作伙伴和购买天数的表中获取平均周期。

huangapple go评论64阅读模式
英文:

Postgresql get average period from a table with different partners and purchase days

问题

Sure, here are the translations of the relevant parts:

"我有一张表格,其中包含合作伙伴和他们下订单的日期。"

"我想获取每个合作伙伴购买周期的信息,例如:"

"如何获取这些间隔?"

Please note that translating code or technical terms can be challenging, and it's often best to use the original terms or provide context in English to ensure clarity.

英文:

So basically I have a table where are partners and the dates when then they did their orders.

partner_id order_date
1 2022-01-02
1 2022-01-20
2 2022-02-20
4 2022-01-15
4 2022-01-17
4 2022-01-30

And I want to have an information of each partner average of purchase period, e.g.

partner_id period
1 18
2 0
4 8

How do I get these:
1 ID partner - (2022-01-20 - 2022-01-02)
2 ID partner - 0
3 ID partner - avg(2022-01-15 - 2022-01-17) + (2022-01-17 - 2022-01-30)))

Would it be possible and how to get these intervals?

答案1

得分: 2

你可以使用 lag() 来获取前一个日期,然后进行聚合:

select partner_id,
    avg(order_date - lag_order_date) as avg_date_diff
from (
    select p.*, 
       lag(order_date) over(partition by partner_id order by order_date) lag_order_date
    from partners p
) p
group by partner_id

请注意,当没有前一行时,lag() 返回 null,然后 avg() 会忽略这些 null 值;这似乎是你想要的行为。

英文:

You can use lag() to get the previous date, then aggregate:

select partner_id,
    avg(order_date - lag_order_date) as avg_date_diff
from (
    select p.*, 
       lag(order_date) over(partition by partner_id order by order_date) lag_order_date
    from partners p
) p
group by partner_id

Note that lag() returns null when there is no previous row, which avg() then ignores; this seems to be what you want.

huangapple
  • 本文由 发表于 2023年6月29日 23:02:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/76582289.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定