我有兩個表格,說費用和付款,我需要計算每個費用的每月支付AVG。SQL AVG和SUM GROUP BY
即Costs_IdCost = 2有3個支付
+-----------+--------------+----------+--------+
| 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 and 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
向我們展示你到目前爲止的情況,那麼即使是這樣的概念,也不可能達到小時,分鐘和秒級。 – MoonKnight
TSQL,MySQL,Oracle,...? –