从sql表计算每日平均销售额

时间:2017-03-22 10:46:07

标签: java sql sql-server jdbc subquery

我想从我的sql表中计算每日平均销售额。 我尝试使用以下查询,但它提供错误说“关键字选择附近的语法不正确”

select avg(select sum(total) from canteen group by date) as average from canteen

4 个答案:

答案 0 :(得分:6)

不要嵌套聚合函数。这就是你想得到每个日期的总和:

select day, sum(total)
from canteen
group by day;

您可以使用子查询获得平均值:

select avg(total)
from (select day, sum(total) as total
      from canteen
      group by day
     ) c;

或者,更简单的替代方案:

select sum(total) / count(distinct day)
from canteen;

答案 1 :(得分:0)

正确的语法是

SELECT date, avg(total) average FROM (
SELECT date, sum(total)total FROM canteen GROUP BY DATE
)AS A
grouP BY date

答案 2 :(得分:0)

如果您不打扰嵌套查询,我更喜欢

select avg(total) from(select sum(total) as total from canteen group by date) as T

答案 3 :(得分:0)

如果您尝试使用这样的子查询,那就更好了:

select avg(total) from(select sum(total) from canteen group by date)