计算每月的平均值并返回单个平均值

时间:2018-04-27 00:56:14

标签: sql jdbc

我计算的每月平均值应该返回一个平均值,所以我做了平均值,它必须是卡车表和订单之间的一对多关系,我使用行映射器为spring jdbc

Select truckId,  truckCode,  purchasedDate, 
descriptions, orderId, petrolQty, orderDate, avg(avgPetrolQty) as avgPerMonth, truckId from (
SELECT  t.truckId, t.truckCode, t.purchasedDate, t.descriptions, o.orderId, o.petrolQty, o.orderDate,
COALESCE(monthname(o.orderDate),'Not Announced') as month,
IFNULL (avg(o.petrolQty),0) as avgPetrolQty  
from truck t left join orderz o 
on t.truckId = o.truckId 
where t.truckId = 3
group by  t.truckCode, o.orderId, o.orderDate
) group by truckCode, orderId

所以我有这样的订单属于truckId 3 这是完整的结果

TRUCKID     TRUCKCODE   PURCHASEDDATE   DESCRIPTION     ORDERID     PETROLQTY   ORDERDATE   AVGPERMONTH     TRUCKID  
3   BY2354  2005-05-01  BLACK TOYOTA 15 1   13.0    2006-01-21  13.0    3
3   BY2354  2005-05-01  BLACK TOYOTA 15 2   53.0    2002-01-21  53.0    3

哪个给了两个avgPermonth我怎样才能写出更好的sql 我上面的sql给出了每月平均值100

这是不正确的,即使我添加更多的订单,它不会改变,直到4个或更多的新订单,然后它给出一些非逻辑平均值,我做错了什么,它的重要我的sql得到两个表orderId可以完整的详细信息如果它影响解决方案,则省略

0 个答案:

没有答案