我有两张桌子。第一个是订阅者。订户也被指定为一个类别。第二个表是订阅者付款。我想知道订阅时间和订阅者的第一次付款之间的平均时间(可以多次)。
这是一段SQL,但它不能做我想做的事 - 虽然我感觉我很接近;)
SELECT category,
AVG(TIMESTAMPDIFF(HOUR, subs.timestamp, MIN(payments.timestamp)))
FROM subs
JOIN payments ON (payments.user_id = subs.user_id)
GROUP BY category
现在我得到“无效使用群组功能” - 因为MIN功能,所以这是不对的。我现在该怎么办?提前谢谢!
答案 0 :(得分:2)
SELECT category,
AVG(TIMESTAMPDIFF(HOUR, subs.timestamp, p.timestamp))
FROM subs
JOIN ( SELECT user_id
, min(timestamp) timestamp
FROM payments
GROUP BY user_id
) p
ON p.user_id = subs.user_id
GROUP BY category
如果您需要使用此查询的结果更新另一个表,您可以执行类似的操作(未经过测试,因此可能存在语法错误,但希望您能得到这个想法)。我假设another_table
有category和avg_hrs_spent列。
UPDATE another_table
SET avg_hrs_spent =
(
SELECT a.avg_hrs_spent FROM
(
(SELECT category,
AVG(TIMESTAMPDIFF(HOUR, subs.timestamp, p.timestamp)) avg_hrs_spent
FROM subs
JOIN ( SELECT user_id
, min(timestamp) timestamp
FROM payments
GROUP BY user_id
) p
ON p.user_id = subs.user_id
GROUP BY category) a
)
WHERE a.category = another_table.category
)