0

我有两张表,比如CostsPayments,我需要计算每项费用的每月支付的 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
4

3 回答 3

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

于 2012-09-26T16:24:08.863 回答
1

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

GROUP BY datepart(MONTH, Cost.Date)

这可能不是最有效的方法,但它可能会很好地工作。BTW datepart 是内置于 MSSQL 的函数中。

于 2012-09-26T14:53:30.247 回答
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]

于 2015-08-14T18:23:04.560 回答