sql连接四个表并计算平均值

时间:2011-09-20 18:39:38

标签: sql join average calculated-columns

我如何获得一个连接这四个表的查询,并给出了平均值?

Table1:
TeamId |   TeamName
  1    |      TA
  2    |      TB
  3    |      TC

Table2:
YearsId  | Years
    1    | 2009-2010
    2    | 2010-2011
    3    | 2011-2012

Table3:
MonthsId | Month
    1    |  July
    2    |  Aug
    3    |  Sept

Table4:
TeamId  | MonthsId  | YearsId  | TeamWinCount
    1   |     1     |    2     |        44
    1   |     1     |    3     |        11
    1   |     2     |    2     |        0
    1   |     12    |    3     |        13
    2   |     1     |    2     |        33

我希望得到如下结果:

   Year    |  Team   | Avg (avg win count jun+aug+sept+.../12)
 2009-2010 |   TA    |   23.3
 2009-2010 |   TB    |   18.23    
 2009-2010 |   TC    |   35.23    
 2010-2011 |   TA    |   18.23    
 2010-2011 |   TB    |   18.23    
 2010-2011 |   TC    |   18.23    

如果一个月没有条目,则应将其计为0

必须有一些天才,以前就是这样做的。我已经玩过加入表格,但似乎无法得到一个平均值的列。非常感谢任何帮助或指导!

2 个答案:

答案 0 :(得分:1)

这里不需要

Table3

SELECT Table2.Years,Table1.TeamName,IFNULL(AVG(TeamWinCount), 0) AS TeamWinCount
FROM Table2
CROSS JOIN Table1
LEFT JOIN Table4 ON Table1.TeamId=Table4.TeamId AND Table2.YearsId=Table4.YearsId
GROUP BY Table2.Years,Table1.TeamName

答案 1 :(得分:1)

好的,因为我看到你的问题首先你需要一个所有可能的年/月/团队组合的列表,然后一旦你有你想要将wincount的任何空值转换为0,那么你想要做平均值

我会尝试一些变化:

select Years, TeamName, avg(wincount)
from 
(Select  Years, Month, TeamName, case when Wincount is null then 0  else  Wincount
from table1 t1
cross join table2 t2
cross join tabl3 t3
left join table4 t4 
on t1.teamid = t4.teamid and t2.yearsId = t4.yearsId
    and t3.MonthsId = t4.monthsId) a
group by Years, TeamName