我发现了一些类似的帖子,但无法弄清楚如何在我的情况下申请。基本上在连接两个表时,我在输出中得到了重复计算。以下是我正在看的内容:
Name | Type | Count
Chris Blue 3
Chris Red 2
Steve Blue 10
Steve Red 5
Steve Green 4
Peter Blue 7
Name | Hours
Chris 2.4
Steve 1.5
Peter 0.2
SELECT t1.name, t1.type, t1.count, t2.hours / count(t1.name) as avg_hrs
FROM t1 JOIN t2 on t1.name = t2.name
GROUP BY t1.name, t1.type
Name | Type | Count | Hours
Chris Blue 3 1.2
Chris Red 2 1.2
Steve Blue 10 0.5
Steve Red 5 0.5
Steve Green 4 0.5
Peter Blue 7 0.2
Name | Type | Count | Hours
Chris Blue 3 2.4
Chris Red 2 2.4
Steve Blue 10 1.5
Steve Red 5 1.5
Steve Green 4 1.5
Peter Blue 7 0.2
'小时'列出错了。基本上,我想将t2中的小时数除以t1中名称的出现次数;相反,我得到了新生成的表中每一行的t2.hours的完整值,当我查看聚合表时,这会导致一堆双/三计数。
有关如何修复的任何想法?谢谢你的任何指示。
答案 0 :(得分:1)
你可以这样做:
select t1.name,
t1.type,
t1.count,
t2.hours/t1count.total as hours
from t1
inner join t2 on (t1.name = t2.name)
inner join
(select name, count(*) total
from t1
group by name) t1count
on (t1.name = t1count.name)
在这里查看小提琴:http://sqlfiddle.com/#!9/27a07a/4