MySQL AVG(TIMESTAMPDIFF) 与 GROUP BY
我有两个表 user (one)
和 transaction (many)
,我需要获取从创建用户到进行第一笔交易的平均时间(以天为单位) 。我正在使用 AVG(TIMESTAMPDIFF)
,它运行良好,除了 GROUP BY
返回每个用户的平均值,而不是 中所有唯一用户的单个平均值。代码>交易
表。如果我删除GROUP BY
,我会得到一个平均数字,但它考虑了用户的多个交易,而我只想为每个用户提供一个交易(他们进行的第一个交易)。
这是我的 SQL:
SELECT AVG(TIMESTAMPDIFF(DAY, u.date_created, t.transaction_date)) AS average
FROM transaction t
LEFT JOIN user u ON u.id = t.user_id
WHERE t.user_id IS NOT NULL AND t.status = 1
GROUP BY t.user_id;
如果有人可以帮助我仅返回唯一用户的平均值,我将不胜感激。将查询分成两个很好,但是表很大,因此返回大量数据并将其放回原处是不行的。提前致谢。
I have two tables user (one)
and transaction (many)
and I need to get the average time in days from when a user was created to when they made their first transaction. I'm using AVG(TIMESTAMPDIFF)
which is working well, except that the GROUP BY
returns an average against every user instead of one single average for all unique users in the transaction
table. If I remove the GROUP BY
, I get a single average figure but it takes into account multiple transactions from users, whereas I just want to have one per user (the first they made).
Here's my SQL:
SELECT AVG(TIMESTAMPDIFF(DAY, u.date_created, t.transaction_date)) AS average
FROM transaction t
LEFT JOIN user u ON u.id = t.user_id
WHERE t.user_id IS NOT NULL AND t.status = 1
GROUP BY t.user_id;
I'd appreciate it if someone can help me return the average for unique users only. It's fine to break the query down into two, but the tables are large so returning lots of data and putting it back in is a no-go. Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我将 LEFT JOIN 替换为 INNER JOIN,因为我认为这就是您想要的,但它并不 100% 等同于您的
WHERE t.user_id IS NOT NULL
。如果需要,请随意放回 LEFT JOIN。
I replaced the LEFT JOIN with an INNER JOIN because I think that's what you want, but it's not 100% equivalant to your
WHERE t.user_id IS NOT NULL
.Feel free to put the LEFT JOIN back if need be.