mySQL SUM以前的分组查询

时间:2014-08-25 19:14:21

标签: mysql sum subquery grouping

我需要获得每个MODEL的聚合结果,该结果总结了先前查询中先前过滤的项目的总数:

SELECT model, ratio, if(count(model)>=3,3,count(model)) AS gearcount 
FROM zfgearinv 
WHERE allocated = 0 AND sold = 0 
GROUP BY model, ratio 
ORDER BY model

在这个查询中,我只显示< = 3项,然后我只想显示那些项目的SUM PER MODEL:

MODEL     RATIO GEARCOUNT
ZF 220A   1.23  2
ZF 220A   1.53  3
ZF 220A   1.75  3
ZF 220A   2     1
ZF 220A   2.45  2
ZF 220V   1.5   3
ZF 220V   1.75  1
ZF 220V   2     3
ZF 220V   2.5   3

所以我的最终输出应该是:

MODEL     TOTAL
ZF 220A   11
ZF 220V   10

1 个答案:

答案 0 :(得分:0)

您需要做的就是使用外部查询包装该查询,其中您执行齿轮箱的总和

SELECT model as MODEL, SUM(gearcount) as TOTAL
FROM
(   SELECT model, ratio, if(count(model)>=3,3,count(model)) AS gearcount 
    FROM zfgearinv 
    WHERE allocated = 0 AND sold = 0 
    GROUP BY model, ratio
) t
GROUP BY model
ORDER BY model