如何获得Max平均值及其按月分组的Id

时间:2016-01-24 22:13:23

标签: mysql sql

我想要按月分组的最大平均值及其ID,

Select FK_Transporter,Month, MAX(avg_rate) as BTPercent
FROM (
    SELECT kpi.FK_Transporter ,kpi.`Month`, AVG(kpi.OnTimeDelivery) as avg_rate
    FROM primarykpi as kpi,transporter as t
        WHERE kpi.FK_Transporter=t.Id and YEAR(kpi.`Month`)=2016
    GROUP BY FK_Transporter, MONTH(kpi.Month)) tp
GROUP BY tp.`Month`

此查询给了我正确的平均值,但ID不正确。无法找到错误。这是此查询的输出

FK_Transporter       Month             MaxAvg
1                    2016-01-01        2.270109534263611
1                    2016-02-01        0.8539329767227173
1                    2016-03-01        0.6764709949493408

FK_transporter在所有错误的记录中都是1。我怎样才能解决这个问题。谢谢。

这是一个小提琴链接 http://sqlfiddle.com/#!9/02d7c/1/0

2 个答案:

答案 0 :(得分:0)

问题是你只在外部查询中按月分组,所以mysql几乎选择了在扫描内部子查询的结果时遇到的第一个fk_transporter值。在外部查询中,您需要获得每月的最大平均值,并将其加入内部子选择以获得结果:

SELECT t2.fk_transporter, t.month, t.btpercent
FROM
(Select `Month`, MAX(avg_rate) as BTPercent
FROM (
    SELECT kpi.FK_Transporter ,kpi.`Month`, AVG(kpi.OnTimeDelivery) as avg_rate
    FROM primarykpi as kpi,transporter as t
        WHERE kpi.FK_Transporter=t.Id and YEAR(kpi.`Month`)=2016
    GROUP BY FK_Transporter, MONTH(kpi.Month)) tp
GROUP BY tp.`Month`) t
INNER JOIN 
(
    SELECT kpi.FK_Transporter ,kpi.`Month`, AVG(kpi.OnTimeDelivery) as avg_rate
    FROM primarykpi as kpi,transporter as t
        WHERE kpi.FK_Transporter=t.Id and YEAR(kpi.`Month`)=2016
    GROUP BY FK_Transporter, MONTH(kpi.Month)) t2
ON t2.Month=t.month and t2.avg_rate=t.btpercent

Sqlfiddle

答案 1 :(得分:-1)

select中的任何非计算列都应包含在Group By

因此,您需要一个新的子查询包装器:

第1步 - 原始SQL(正确):

SELECT kpi.FK_Transporter, kpi.Month, AVG(kpi.OnTimeDelivery) avg_rate
FROM primarykpi kpi, transporter t
WHERE kpi.FK_Transporter=t.Id and YEAR(kpi.Month)=2016
GROUP BY 1,2

第2步 - 查找具有最高AVG的月份

SELECT tp.Month, max(tp.avg_rate) max_avg_rate
FROM (
    SELECT kpi.FK_Transporter, kpi.Month, AVG(kpi.OnTimeDelivery) avg_rate
    FROM primarykpi kpi, transporter t
    WHERE kpi.FK_Transporter=t.Id and YEAR(kpi.Month)=2016
    GROUP BY 1,2
) as tp
GROUP BY 1

步骤3 - 加入第1步以找到最终结果:

SELECT tp.*
FROM (
    SELECT tp.Month, max(tp.avg_rate) max_avg_rate
    FROM (
        SELECT kpi.FK_Transporter, kpi.Month, AVG(kpi.OnTimeDelivery) avg_rate
        FROM primarykpi kpi, transporter t
        WHERE kpi.FK_Transporter=t.Id and YEAR(kpi.Month)=2016
        GROUP BY 1,2
    ) as tp
    GROUP BY 1
) as t2, (
        SELECT kpi.FK_Transporter, kpi.Month, AVG(kpi.OnTimeDelivery) avg_rate
        FROM primarykpi kpi, transporter t
        WHERE kpi.FK_Transporter=t.Id and YEAR(kpi.Month)=2016
        GROUP BY 1,2
) as tp
WHERE t2.Month=tp.Month and t2.max_avg_rate=tp.avg_rate