gpt4 book ai didi

mysql - 计算 SQL 中日期之间的平均时间

转载 作者:行者123 更新时间:2023-12-04 08:49:51 25 4
gpt4 key购买 nike

使用 MySQL,我试图弄清楚如何回答这个问题:创建第 N 个项目的用户之间的平均月数是多少?
预期结果:

| project count | Average # months |
| 1 | 0 | # On average, it took 0 months to create the first project (nothing to compare to)
| 2 | 12 | # On average, it takes a user 12 months to create their second project
| 3 | 3 | # On average, it takes a user 3 months to create their third project
我的 MySQL 表代表用户创建的项目。该表可以概括为:
| user_id | project created at |
|---------|--------------------|
| 1 | Jan 1, 2020 1:00 pm|
| 1 | Feb 2, 2020 3:45 am|
| 1 | Nov 6, 2020 0:01 am|
| 1 | Mar 4, 2021 5:01 pm|
|------------------------------|
| 2 | Another timestamp |
| 2 | Another timestamp |
| 2 | Another timestamp |
| 2 | Another timestamp |
| 2 | Another timestamp |
| 2 | Another timestamp |
|------------------------------|
| ... | Another timestamp |
| ... | Another timestamp |
有些用户只有一个项目,而有些用户可能有数百个。
编辑:当前实现
with
paid_self_serve_projects_presentation as (
select
`Paid Projects`.owner_email
`Owner Email`,
row_number() over (partition by `Paid Projects`.owner_uuid order by created_at)
`Project Count`,
day(`Paid Projects`.created_at)
`Created Day`,
month(`Paid Projects`.created_at)
`Created Month`,
year(`Paid Projects`.created_at)
`Created Year`,
`Paid Projects`.created_at
`Created`
from self_service_paid_projects as `Paid Projects`
order by `Paid Projects`.owner_uuid, `Paid Projects`.created_at
)

select `Projects`.* from paid_self_serve_projects_presentation as `Projects`

最佳答案

您可以使用窗口函数。我在想 row_number()枚举按创建日期排序的每个用户的项目,以及lag()获取上一个项目的创建日期:

select rn, avg(datediff(created_at, lag_created_at)) avg_diff_days
from (
select t.*,
row_number() over(partition by user_id order by created_at) rn,
lag(created_at, 1, created_at) over(partition by user_id order by created_at) lag_created_at
from mytable t
) t
group by rn
这为您提供了平均天数差异,这在某种程度上更准确。如果你真的想要几个月,那么使用 timestampdiff(month, lag_created_at, created_at)而不是 datediff() - 但请注意,该函数返回一个整数值,因此会损失精度。

关于mysql - 计算 SQL 中日期之间的平均时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64145457/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com