我有一个带有visitor_id,country,time_of_visit的mysql表。
我希望按国家/地区获得平均访问时间。
为了获得持续时间,我得到每个visitor_id的最早和最晚time_of_visit之间的差异。
所以这让我得到了所有访问的平均持续时间:
SELECT AVG(duration)
FROM
(
SELECT TIMESTAMPDIFF(SECOND, MIN(time_of_visit), MAX(time_of_visit))/60
as duration
FROM tracker
GROUP BY visitor_id
) as tracker
有效。但是按国家分组,我失败了。以下是我最近按国家/地区获得平均持续时间的尝试:
SELECT country, AVG(duration)
FROM
(
SELECT TIMESTAMPDIFF(SECOND, MIN(time_of_visit), MAX(time_of_visit))/60
as duration
FROM tracker
GROUP BY visitor_id
) as tracker
GROUP BY country
我得到的错误是:'字段列表'中的未知列'country'。
我认为这应该很简单,但我是个菜鸟。我搜索了很多,尝试了很多想法,但没有好处。有什么帮助吗?
提前致谢。
答案 0 :(得分:0)
您需要在子查询中指定要在外部查询中显示的列 试试这个::
SELECT country, AVG(duration)
FROM
(
SELECT TIMESTAMPDIFF(SECOND, MIN(time_of_visit), MAX(time_of_visit))/60
as duration, country
FROM tracker
GROUP BY visitor_id
) as tracker
GROUP BY country
您也可以尝试:
SELECT
country,
AVG(TIMESTAMPDIFF(SECOND, MIN(time_of_visit), MAX(time_of_visit))/60) as avgTime
FROM
GROUP BY visitor_id,country
答案 1 :(得分:0)
您应该将COUNTRY添加到内部GROUP BY和字段列表
SELECT country, AVG(duration)
FROM
(
SELECT TIMESTAMPDIFF(SECOND, MIN(time_of_visit), MAX(time_of_visit))/60
as duration,country,visitor_id
FROM tracker
GROUP BY visitor_id,country
) as tracker
GROUP BY country
答案 2 :(得分:0)
您必须在子查询中选择国家/地区列,然后必须从派生表tracker.country
SELECT tracker.country, AVG(tracker.duration)
FROM
(
SELECT TIMESTAMPDIFF(SECOND, MIN(time_of_visit), MAX(time_of_visit))/60
as duration ,country
FROM tracker
GROUP BY visitor_id
) as tracker
GROUP BY tracker.country
修改强>
在子选择
GROUP BY
中使用visitor_id
会为您提供记录 包含国家/地区的重复数据以及同时使用GROUP BY
的数据visitor_id,country
会将国家/地区的数据分组 访客ID,这只有在一个访客属于更多时才可能 一个国家,如果一个访客只属于一个国家 即一对一的关系,然后只使用GROUP BY visitor_id