我有两个表user (one)
和transaction (many)
,我需要获得从创建用户到完成第一笔交易的平均时间。我正在使用效果良好的AVG(TIMESTAMPDIFF)
,除了GROUP BY
针对每个用户返回平均值,而不是transaction
表中所有唯一身份用户的平均值。如果我删除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;
如果有人可以帮助我返回唯一身份用户的平均值,我会很感激。可以将查询分解为两个,但是表格很大,因此返回大量数据并将其重新放入是不行的。提前谢谢。
答案 0 :(得分:2)
SELECT AVG(TIMESTAMPDIFF(DAY, S.date_created, S.transaction_date)) AS average
FROM (
SELECT u.date_created, t.transaction_date
FROM transaction t
INNER JOIN user u ON u.id = t.user_id
WHERE t.status = 1
GROUP BY t.user_id
HAVING u.date_created = MIN(u.date_created)
) s
我用INNER JOIN替换LEFT JOIN,因为我认为这就是你想要的,但它与你的WHERE t.user_id IS NOT NULL
不是100%相等。
如果需要,请随意将LEFT JOIN放回去。
答案 1 :(得分:2)
select avg( TIMESTAMPDIFF(DAY, u.date_created, min_tdate) ) as average
from user u
inner join
(select t.user_id, min(t.transaction_date) as min_tdate
from transaction t
where t.status=1;
group by t.user_id
) as min_t
on u.id=min_t.user_id;