作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
以下 SQL 查询:
SELECT DISTINCT b.browserSessionId, v.visitDay, b.sessionTime
FROM visit AS v
INNER JOIN bsession AS b
ON v.browserSessionId=b.browserSessionId
给我这个结果:
browserSessionId visitDay sessionTime
100 20150914 150
101 20150914 100
102 20150914 50
103 20150915 75
104 20150915 150
114 20150915 225
结果我想要的是按 visitDay 分组的平均 sessionTimes:
visitDay sessionTime
20150914 50
20150915 75
这个查询给了我错误的结果:
SELECT DISTINCT b.browserSessionId, v.visitDay, AVG(b.sessionTime)
FROM visit AS v
INNER JOIN bsession AS b
ON v.browserSessionId=b.browserSessionId
GROUp BY v.visitDay
browserSessionId visitDay AVG(b.sessionTime)
100 20150914 100.0000
103 20150915 142.5000
它不是为每个 bowserSessionId 计算不同的值,而是计算 vist 表中 browserSession 每次出现的平均 sessionTime:
SELECT b.browserSessionId, v.visitDay, b.sessionTime
FROM visit AS v
INNER JOIN bsession AS b
ON v.browserSessionId=b.browserSessionId
browserSessionId visitDay sessionTime
100 20150914 150
100 20150914 150
100 20150914 150
101 20150914 100
101 20150914 100
101 20150914 100
101 20150914 100
102 20150914 50
102 20150914 50
102 20150914 50
103 20150915 75
103 20150915 75
103 20150915 75
103 20150915 75
104 20150915 150
104 20150915 150
104 20150915 150
114 20150915 225
114 20150915 225
114 20150915 225
如何让 SQL 只计算不同的 sessionTime 值?
最佳答案
使用子查询:
SELECT t.browserSessionId, t.visitDay, AVG(t.sessionTime)
FROM
(
SELECT DISTINCT b.browserSessionId, v.visitDay, b.sessionTime
FROM visit AS v
INNER JOIN bsession AS b
ON v.browserSessionId=b.browserSessionId
) AS t
GROUP BY t.browserSessionId, t.visitDay;
或取决于聚合级别
SELECT t.visitDay, AVG(t.sessionTime)
FROM
(
SELECT DISTINCT b.browserSessionId, v.visitDay, b.sessionTime
FROM visit AS v
INNER JOIN bsession AS b
ON v.browserSessionId=b.browserSessionId
) AS t
GROUP BY t.visitDay;
关于mysql - 用双 GROUP BY 计算 AVG,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32560846/
我是一名优秀的程序员,十分优秀!