2012-09-26 241 views
0

我有兩個表格,說費用付款,我需要計算每個費用的每月支付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 
+0

向我們展示你到目前爲止的情況,那麼即使是這樣的概念,也不可能達到小時,分鐘和秒級。 – MoonKnight

+0

TSQL,MySQL,Oracle,...? –

回答

1

您可以按日期的月份部分組。

GROUP BY datepart(MONTH, Cost.Date) 

這可能不是最有效的方式,但它可能很好地工作。 BTW datepart是建立在MSSQL的功能。

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

0

我用的

選定條目類似
SELECT format(DATE_TIME,''yyyy-MM'') as [Month], ....... 

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

排序BY與我使用的GROUP BY相同。如果你想 例如:SELECT format(DATE_TIME,''yyyy-MM-dd.HH'') as [Hour]