我有两个表
event
和trans
。
CREATE TABLE `event` (
`event_name` varchar(40) DEFAULT NULL,
`user_id` varchar(40) DEFAULT NULL,
`time` timestamp
);
CREATE TABLE `trans` (
`item_id` varchar(40) DEFAULT NULL,
`quantity` int(11) DEFAULT NULL,
`price` decimal(10,0) DEFAULT NULL,
`user_id` varchar(40) DEFAULT NULL,
`time` timestamp
)
假设事件表的值(多次访问):
|visit |a1 |2016-09-14 22:48:14 | |visit |a2 |2016-09-14 22:48:28 | |visit |a3 |2016-09-14 22:48:45 | |visit |a1 |2016-09-15 15:10:39 | |visit |a2 |2016-09-15 15:11:08 | |visit |a1 |2016-09-15 15:12:34 |
和用于转换表
|i1 |1 |100 |a1 |2016-09-15 15:12:22 | |i2 |2 |100 |a2 |2016-09-15 15:13:17 | |j1 |1 |140 |a1 |2016-09-15 16:12:22 | |j4 |3 |150 |a3 |2016-09-15 16:13:17 |
我写了一个查询来查找用户首次访问和首次购买之间的平均时间。
SELECT AVG(timestampdiff(second, e.mintime, t.mintime))
FROM (SELECT user_id, min(time) AS mintime
FROM event e
GROUP BY user_id
) e JOIN
(SELECT user_id, min(time) AS mintime
FROM trans t
GROUP BY user_id
) t
ON e.user_id = t.user_id;
但是现在我想针对每个item_id查找首次访问和购买之间的平均时间。
对于以上数据,我该如何编写查询来查找...
每个item_id从首次访问到购买的平均时间。
答案 0 :(得分:1)
这怎么样?这是我能想到的最接近的东西。
SELECT *, timestampdiff(second, e.`time`, t.`time`) as difference
FROM `event` e
left join trans as t ON t.user_id = e.user_id -- same use
AND YEAR(e.`time`) = YEAR(t.`time`) -- same year
AND MONTH(e.`time`) = MONTH(t.`time`) -- same month
AND DAY(e.`time`) = DAY(t.`time`) -- same day
AND t.`time` between e.`time` AND ADDTIME( e.`time`,"0:10:00") -- ten minutes RANGE
order by e.user_id, YEAR(e.`time`), MONTH(e.`time`), DAY(e.`time`), e.`time`
;
我不确定哪个是父母表。尝试切换左连接表声明并重新修改RANGE条件。
答案 1 :(得分:0)
如果我的理解正确,那么您希望每个购买该商品的用户从首次访问到购买该商品的平均值。
如果是这样,则可以将item_id
添加到第二个子查询中,然后在外部查询中将其用于聚合:
SELECT t.item_id, AVG(timestampdiff(second, e.mintime, t.mintime))
FROM (SELECT user_id, min(time) AS mintime
FROM event e
GROUP BY user_id
) e JOIN
(SELECT user_id, item_id, min(time) AS mintime
FROM trans t
GROUP BY user_id, item_id
) t
ON e.user_id = t.user_id
GROUP BY t.item_id;