寻找平均每日价值

时间:2018-08-23 22:43:59

标签: sql average

此表包含日期和在不同商店的苹果的价格。最终,我希望SQL报告结果“ $ 3.5”,这是两天内苹果的平均成本。如何在下面修改我的查询?

Select Date, sum(AppleCost) from table where Date between '2018-08-21' and '2018-08-22'
and group by Date;

数据:

[Date,AppleCost]

[08-22,$5]

[08-22,$1]

[08-23,$4]

2 个答案:

答案 0 :(得分:0)

像以前一样按天分组,以获取每天的总和,然后从该结果中选择平均值。

SELECT avg(pnl) pnl
       FROM (SELECT sum(totalpnl) pnl
                    FROM table
                    WHERE tradedate BETWEEN '2018-08-21'
                                            AND '2018-08-22'
                    GROUP BY tradedate) x;

答案 1 :(得分:0)

您可以执行两次avg。编写子查询,使用where子句获取期望的日期。要按日期获取avg,请在主查询中再执行一次avg

CREATE TABLE T
(
     DATE DATE,
     AppleCost INT
);

INSERT INTO T VALUES ('2018-08-22', 5);
INSERT INTO T VALUES ('2018-08-22', 1);
INSERT INTO T VALUES ('2018-08-23', 4);

查询1

SELECT 
    AVG(dayAvg) 
FROM
    (SELECT DATE, AVG(AppleCost) dayAvg
     FROM T 
     WHERE DATE BETWEEN '2018-08-22' AND '2018-08-23'
     GROUP BY DATE) t

Results

| avg(dayAvg) |
|-------------|
|         3.5 |