SUM的SQL AVG

时间:2015-04-28 14:00:55

标签: mysql sql mysql-workbench

我想获得计算average的{​​{1}}。我试过this stackoverflow answer的语法所以我的SQL查询看起来像这样:

sum

然而,这并没有给我一个正确的平均值。我希望每年获得平均SELECT AVG(iq.stockvalue_sum), iq.date FROM( SELECT CONCAT(DATE_FORMAT(s.date, '%Y'), '-01-01') as date, SUM(GREATEST(s.stockvalue,0)) as stockvalue_sum FROM stockvalues s GROUP BY CONCAT(DATE_FORMAT(s.date, '%Y'), '-01-01') ) iq 。该表背后的想法是每天保存每种产品的库存和库存值。因此,此特定查询将显示其拥有数据的每年的平均股票价值。

编辑:示例输出数据

stockvalue

输入数据:

Stockvalue | Year
_________________
-  205     | 2015
-  300     | 2014

所以我需要计算知道pid | val | date ______________________ - 1 | 100 | 28-04-2015 - 2 | 150 | 28-04-2015 - 1 | 80 | 27-04-2015 - 2 | 80 | 27-04-2015 .... - 1 | 100 | 29-01-2014 - 2 | 100 | 29-01-2014 - 1 | 200 | 30-01-2014 - 2 | 200 | 30-01-2014 股票价值的平均值。所以第X天所有股票价值的总和和X的平均值

2 个答案:

答案 0 :(得分:4)

至少在外部查询中缺少group by

SELECT AVG(iq.stockvalue_sum), iq.date
FROM(
    SELECT CONCAT(DATE_FORMAT(s.date, '%Y'), '-01-01') as date,
    SUM(GREATEST(s.stockvalue,0)) as stockvalue_sum
    FROM stockvalues s
    GROUP BY CONCAT(DATE_FORMAT(s.date, '%Y'), '-01-01')
) iq
GROUP BY iq.date

但是,如果您的内部查询返回带有求和值的单年,则该值的平均值将相同。也许你可以澄清你的意图。你确定你需要内部查询吗?也许这就是你所需要的一切?

select avg(GREATEST(stockvalue,0)), CONCAT(DATE_FORMAT(s.date, '%Y'), '-01-01') as date
from stockvalues 
group by CONCAT(DATE_FORMAT(s.date, '%Y'), '-01-01')

答案 1 :(得分:1)

我认为您需要按日期对内部查询进行分组,并按年份对外部查询进行分组以获得您所追求的结果:

SELECT  AVG(s.Stockvalue) AS Stockvalue
        YEAR(s.Date) AS Date
FROM    (   
            SELECT  DATE(s.Date) AS Date, 
                    SUM(GREATEST(s.stockvalue,0)) AS Stockvalue 
            FROM    stockvalues AS s 
            GROUP BY DATE(s.Date)
        ) AS s
GROUP BY YEAR(s.Date);