在输出MySQL中添加列平均值

时间:2014-11-14 18:21:22

标签: mysql join average

我想在现有输出中添加一列AVG。首先,我用INNER JOIN计算电力和天然气的使用量。但是现在我要添加AVG" Day hour"到输出。

表格列

Id, Datum, Tijd, consumed_rate1, consumed_rate2, gas

当我想要使用consume_rate1,consume_rate2和gas时输出最后24条记录时,我使用此查询:

SELECT
    A.Datum AS Datum,
    A.Tijd AS Tijd,
    A.Daguur AS Daguur,
    A.Aantal AS Aantal,
    A.Consumed_rate1 + A.Consumed_rate2 AS Elektra,
    (A.Consumed_rate1 + A.Consumed_rate2 - B.Consumed_rate1 - B.Consumed_rate2) AS 'Elektra verbruikt',
    A.gas AS Gas, (A.gas - B.gas) AS 'Gas verbruikt' 
FROM smartmeter A 
INNER JOIN smartmeter B ON B.id = (A.id-1) 
ORDER BY A.Id DESC   
LIMIT 24

现在我想添加一个包含来自consume_rate1 + consume_rate2和gas的使用AVG的列。我想我必须与LEFT JOIN合作,但我不知道如何。是否有任何机构可以帮助我?

1 个答案:

答案 0 :(得分:0)

尝试这样的事情:

SELECT 
    AVG(Elektra), AVG(Gas)
FROM(
    SELECT
        A.Datum AS Datum,
        A.Tijd AS Tijd,
        A.Daguur AS Daguur,
        A.Aantal AS Aantal,
        A.Consumed_rate1 + A.Consumed_rate2 AS Elektra,
        (A.Consumed_rate1 + A.Consumed_rate2 - B.Consumed_rate1 - B.Consumed_rate2) AS 'Elektra verbruikt',
        A.gas AS Gas, (A.gas - B.gas) AS 'Gas verbruikt',
    FROM smartmeter A 
    INNER JOIN smartmeter B ON B.id = (A.id-1) 
    ORDER BY A.Id DESC   
    LIMIT 24
) as a