SQL AVG和SUM GROUP BY

时间:2012-09-26 14:43:40

标签: mysql subquery sum average

我有两张表,比如费用付款,我需要计算每笔费用的每月付款的AVG。

即。 Costs_IdCost = 2有三笔付款

+-----------+--------------+----------+--------+
| IdPayment | Costs_IdCost |   Date   | Amount |
+-----------+--------------+----------+--------+
|     1     |      2       |2012/09/10|  1000  |
+-----------+--------------+----------+--------+
|     2     |      2       |2012/09/20|  3000  |
+-----------+--------------+----------+--------+
|     3     |      2       |2012/10/01|  5000  |
+-----------+--------------+----------+--------+

现在我不仅需要支付的平均值(3000),还需要平均值:

September : (1000+3000)/2 = 2000
October   : 5000 /1 = 5000
AVG       : (2000+5000)/2 = 3500

我对group by和子查询> _<

非常混乱 谢谢你!

-------------------- EDIT ----------------------- ----

我正在使用mySql,这是我到目前为止所做的:

SELECT c.IdCost,
c.Name,
c.Amount,
AVG(p.monthly_sum) Mean,
SUM( p.Amount ) Total,
COUNT( p.IdPayment ) Num
FROM Costs c
LEFT JOIN (SELECT MONTH(Date), 
        YEAR(Date), 
                    Costs_IdCost,
                    IdPayment,
                    Amount,
        AVG (Amount) monthly_sum
    FROM Payments
    GROUP BY YEAR(Date), MONTH(Date) 
     ) p ON p.Costs_IdCost = c.IdCost
GROUP BY c.IdCost

3 个答案:

答案 0 :(得分:2)

我不确定这是否正是您所期待的,但它会为您提供所需的结果:

select date_format(date, '%Y-%m') Month,
  avg(amount) AvgAmount
from costs c
left join payments p
  on c.id = p.costs_idcost
group by date_format(date, '%Y-%m')
union all
select concat(cast(count(*) as char), ' Months Averaged'),
  avg(AvgAmount) TotalAvg
from
(
  select avg(amount) AvgAmount, 
    date_format(date, '%Y-%m') Month
  from costs c
  left join payments p
    on c.id = p.costs_idcost
  group by date_format(date, '%Y-%m')
) x

请参阅SQL Fiddle with Demo

答案 1 :(得分:1)

您可以按月份分组日期。

GROUP BY datepart(MONTH, Cost.Date)

这可能不是最有效的方式,但它可能很好用。 BTW datepart是在MSSQL的功能中构建的。

答案 2 :(得分:0)

我使用

的选择条目做类似的事情
SELECT format(DATE_TIME,''yyyy-MM'') as [Month], .......

GROUP BY format(DATE_TIME,''yyyy-MM''), .........

SORT BY与我使用的GROUP BY相同。如果你愿意的话,这个概念甚至不能达到小时,分钟和二级 例如:SELECT format(DATE_TIME,''yyyy-MM-dd.HH'') as [Hour]