SQL连接表并获得平均值

时间:2014-09-09 15:09:49

标签: mysql

我昨天问了一个类似的问题(我认为这是我的问题,但后来我意识到有一个错误)。但是这个问题得到了很好的答案,改变这个问题没有意义。我认为这个问题已经足够不同了。

问题:

我有四张桌子,我需要计算每所学校的平均分数。

问题:学校平均分应按每个团队获得的两个最新积分计算。目前,查询计算了团队平均获得的所有积分。

学校可以拥有多个团队,团队可以拥有多个积分。并且每个团队只应在学校平均值中计算两个最新点。每所学校还应获得适当的城市KAID(CITY_ID)。在sqlFiddle中一切正常但平均值是错误的,因为它计算了团队获得的所有点数。

我创建了一个简化的工作:sqlFiddle

SCHOOL1的平均值应为2,66 ......

示例:

让我们说Team10有6分:

TEAM10 3..4..7..0..3..5 = 8 (3+5=8)

只应以平均值计算最新的两个点(3和5)。所有团队都应该这样做。

我尝试过几次查询,但它们无法正常工作。

查询1(问题:计算所有点数):

SELECT SNAME As School, AVG(PTS) As Points, ka.KAID As City_id FROM
     Schools op
     LEFT JOIN Points pi
     ON op.OPID = pi.OPID
     LEFT JOIN Citys ka
     ON op.KAID = ka.KAID
     GROUP BY SNAME, ka.KAID
     ORDER BY City_id, Points, School ASC

查询2(问题:平均错误和重复):

SELECT IFNULL(AVG(PTS), 0) AS AVG, po2.KAID AS KID, SNAME AS SNAM FROM 
    (
    SELECT te1.ID, te1.KAID, po1.PTS, te1.OPID FROM Points po1
    INNER JOIN Teams te1 ON te1.ID = po1.TEID
    GROUP BY po1.TEID, te1.ID HAVING count(*) >= 2
    )
po2 INNER JOIN Schools sch1 ON po2.KAID = sch1.KAID
    GROUP BY sch1.SNAME, sch1.OPID
    ORDER BY po2.ID DESC

我对sql很新,我尝试了不同的查询,但我没有让它正常工作。

如果问题不明确,请问我会尝试更好地解释。

1 个答案:

答案 0 :(得分:1)

尝试运行此...

SELECT 
    SNAME As School, 
    SUM(pts)/ count(*) As Points, 
    ka.KAID As City_id 
FROM Schools op
LEFT JOIN Points pi
   ON op.OPID = pi.OPID
LEFT JOIN Citys ka
   ON op.KAID = ka.KAID
GROUP BY SNAME, ka.KAID
ORDER BY City_id, Points, School ASC

DEMO

从我看到你对第一所学校和第一个城市的8行总和= 29 29/8 = 3.25 ..你正在加入正确字段的表格,查询返回基于opid和kaid的表中的行,所以看起来结果是正确的...我猜avg函数不是包括0或其他,但结果是

编辑:

要获得两个最新的行,你需要查看每个学校最大的id,然后是第二个最好的..这将做你想要的。

SELECT 
    SNAME As School, 
    SUM(pts)/ count(*) As Points, 
    ka.KAID As City_id 
FROM Schools op
LEFT JOIN Points pi ON op.OPID = pi.OPID
LEFT JOIN Citys ka ON op.KAID = ka.KAID
JOIN
(   (   SELECT MAX(id) as f_id 
        FROM points
        GROUP BY TEID
        ORDER BY f_id
    )
    UNION
    (   SELECT p1.id 
        FROM
        (   SELECT MAX(id) as t_id 
            FROM points
            GROUP BY TEID
            ORDER BY t_id
        )t
        LEFT JOIN points p1 on p1.id = (t.t_id -1)
    )
) temp ON temp.f_id = pi.id
GROUP BY SNAME, ka.KAID
ORDER BY City_id, Points, School ASC;

ANOTHER DEMO