gpt4 book ai didi

mysql - 用双 GROUP BY 计算 AVG

转载 作者:行者123 更新时间:2023-11-28 23:51:08 25 4
gpt4 key购买 nike

以下 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com