我有两张表,比如Costs和Payments,我需要计算每项费用的每月支付的 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 和 subquery 变得非常混乱>_<
谢谢你!
- - - - - - - - - - 编辑 - - - - - - - - - - - - - -
我正在使用 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